Last Updated: August 15, 2019
·
527
· polysign

Fun with Lamda in Ruby

Oh I love lambdas. They can be so much fun :)

While browing the web I came across some Python code. Lambdas are commonly used in Python, as in Ruby.

So I was wondering if I could implement the same example in Ruby.

Here is the code which will show the main idea:

def base_calc(x)
  lambda{|y| x + y}
end

calc = base_calc(10)

calc.call(1)
=> 11

calc.call(21)
=> 31

The main idea is to have a method which can receive a base parameter, or config. The method itself will then return a Lambda which can receive additional parameters which can interact with the base parameter.

Instead of just returning a single Lambda, imagine returning multiple Lambdas inside an array or a hash.

Can you think of any cool examples on how to use this?