Ruby/Method/lambda

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Invoking Blocks

block = lambda { |x| puts x }          # RIGHT
block.call "Hello World!"
# Hello World!



It"s possible to store code blocks within variables, using the lambda method

print_parameter_to_screen = lambda { |x| puts x }
print_parameter_to_screen.call(100)



Provide different number of parameters for lambda

l = lambda {|x,y| print x,y }
l.call(1,2)     # This works
l.call(1)       # Wrong number of arguments
l.call(1,2,3)   # Wrong number of arguments
l.call([1,2])   # Wrong number of arguments
l.call(*[1,2])  # Works: explicit splat to unpack the array



return a lambda function

  def n_times(thing)
    return lambda {|n| thing * n }
  end
  p1 = n_times(23)
  p1.call(3)
  p1.call(4)
  p2 = n_times("Hello ")
  p2.call(3)



Use lambda to create a block

#!/usr/bin/env ruby
prc = lambda { |name| puts "Hello, " + name }
prc. call "myValue!"



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)