Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Use lambda in Ruby (See related posts)

Source: Robert Sosinski » Understanding Ruby Blocks, Procs and Lambdas [robertsosinski.com]

class Array
  def iterate!(code)
    self.each_with_index do |n, i|
      self[i] = code.call(n)
    end
  end
end
 
array_1 = [1, 2, 3, 4]
array_2 = [2, 3, 4, 5]
 
square = lambda { |n|  n ** 2}
 
array_1.iterate!(square)
array_2.iterate!(square)
 
puts array_1.inspect
puts array_2.inspect
 
# => [1, 4, 9, 16]
# => [4, 9, 16, 25]


This is eactly the same code as creating a proc [dzone.com] except the statement Proc.new has been changed to lambda. Lambda is slightly more advanced than Proc, as lambda handles specific code scenarios in a more controlled manner specifically validating the number of arguments supplied and allowing code to continue past an initial nested return statement. e.g.

# example-12.rb
 
def generic_return(code)
  one, two    = 1, 2
  three, four = code.call(one, two)
  return "Give me a #{three} and a #{four}"
end
 
puts generic_return(lambda { |x, y| return x + 2, y + 2 })
 
puts generic_return(Proc.new { |x, y| return x + 2, y + 2 })
 
puts generic_return(Proc.new { |x, y| x + 2; y + 2 })
 
puts generic_return(Proc.new { |x, y| [x + 2, y + 2] })
 
# => Give me a 3 and a 4
# => *.rb:11: unexpected return (LocalJumpError)
# => Give me a 4 and a 
# => Give me a 3 and a 4


Finally just to recap a Proc is a type of block however a Proc can be implemented independently from the context in which it is finally used e.g.

square = Proc.new {|n| n** 2}




Comments on this post

asil posts on Oct 23, 2009 at 16:50
Thank you for sharing and technical informations. This article I want to share with my other friends. Regards.

- - - - - - - - - - - - - - - - - - - - - - - -
Eglence icin Chat, Sohbet deneyin.

You need to create an account or log in to post comments to this site.


Click here to browse all 7305 code snippets

Related Posts