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

Closures and Higher-Order Functions

Closures and Higher-Order Functions

In this lesson — part of Advanced Features — you'll learn closures and higher-order functions in Ruby and why it matters in real work.

Why it matters

Functions that take or return functions unlock concise, composable code.

Key ideas

  • Functions as values
  • map / filter / reduce
  • Callbacks
  • Composition

In practice

Here's how it looks in idiomatic Ruby:

nums = [1, 2, 3, 4, 5, 6]
evens   = nums.select { |n| n.even? }   # filter
doubled = nums.map    { |n| n * 2 }     # transform
puts evens.inspect      # => [2, 4, 6]
puts doubled.inspect    # => [2, 4, 6, 8, 10, 12]

Ruby note: Enumerable methods like map and select (filter) take a block and return a new array, leaving the original untouched; reject is the inverse of select.

Try it yourself

Exercise: In Ruby, use map and filter to get the squares of the even numbers.

Recap

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