Use lambda to create a list of function : lambda « Method « Ruby






Use lambda to create a list of function


def times_n(n)
  lambda { |x| x * n }
end
times_ten = times_n(10)
times_ten.call(5)                                    # => 50
times_ten.call(1.25)                                 # => 12.5

circumference = times_n(2*Math::PI)
circumference.call(10)                               # => 62.8318530717959
circumference.call(3)                                # => 18.8495559215388
p [1, 2, 3].collect(&circumference)

 








Related examples in the same category

1.It's possible to store code blocks within variables, using the lambda method
2.Use lambda to create a block
3.Invoking Blocks
4.return a lambda function
5.Provide different number of parameters for lambda