Skip to main content

Posts

Showing posts from September, 2012

Passing Functions and Lambdas into Functions with Ruby

Ruby's New Style of Lambda Functions f = ->( m ) { p m } f.call( 1 ) #=> 1 Which of course means the same thing as: f = lambda { |n| p n } f.call(1) #=> 1 Ruby Proc Objects p = Proc.new { |n| p n + 2 } p.call(2) #=> 4 Using a Function as a Closure in Ruby def domo( k ) ->(m) { p m + k } end z = domo( 5 ) z.call( 5 ) #=> 10 Function :domo takes a single parameter. Within :domo , we create a lambda that takes a single parameter, and adds that parameter to the value :domo takes in as its parameter. Then, we assign z to be the result of the lambda in :domo with its 'k' parameter loaded with 5. When z is called, we pass (another) 5 to it. This parameter loads the lambdas n parameter. The lambda executes, essentially adding n (5) + k (5) and yielding the result of 10. The thing about closures such as this is, we can load the initial value of the lambda to be whatever we want it to be when assigning the function :domo '