Free preview.You're sampling one lesson — enroll free to unlock all 8 lessons and track your progress.
Enroll free
lesson

Pure Functions

Pure Functions

In this lesson — part of Functional Foundations — you'll learn pure functions in Ruby and why it matters in real work.

Why it matters

Functional style — pure functions and immutability — makes code easier to test and reason about.

Key ideas

  • Pure functions
  • Immutability
  • No shared mutable state
  • Predictable outputs

In practice

Here's how it looks in idiomatic Ruby:

def square(n)
  n * n            # depends only on input, no side effects
end
puts square(5)     # => 25, always
puts square(5)     # => 25, referentially transparent

Ruby note: A pure function's result depends solely on its arguments with no external state or side effects, so calling it repeatedly with the same input always yields the same value.

Try it yourself

Exercise: In Ruby, rewrite a function that mutates a global so it's pure.

Recap

You now understand pure functions and can apply it in Ruby. Mark this lesson complete and continue to the next one.