Power Tools: Blocks & Enumerable Methods
9 min · Ruby
Write inline blocks and transform arrays with map and select.
Enemy 1 of 5
Lambdas: functions as values
A lambda is a small unnamed function stored in a variable. This one squares a number, and .call runs it with 6. Press Run to see it.
Why this works
A lambda is a compact, unnamed ("anonymous") function that you can store in a variable, pass around, and call later, written as ->(params) { body }. This is different from the def ... end methods you've used so far, which are always named and attached to the program globally the moment they're defined; a lambda is just a value, like a string or a number, that happens to be callable.
You call a lambda with .call(args) (there are shorthand alternatives like square.(6) or square[6], but .call is the clearest to read as a beginner). Storing logic this way is especially useful when you want to hand a small calculation to another method, as you'll see with .map and .select below.