All lessons

Power Tools: Blocks & Enumerable Methods

9 min · Ruby

Write inline blocks and transform arrays with map and select.

Ruby · Power Tools: Blocks & Enumerable Methods0/5 cleared

Enemy 1 of 5

Lambdas: functions as values

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.

You
Binary Treant

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 36