RSS Amplifier

jpterry.com · Mar 7, 2012

passing objects to methods as blocks in ruby

0
Sign in to vote or save

This page cannot be shown here. You can still read it on the original site — the toolbar below keeps your place in the directory.

Lambda’s can come in handy when you need to apply a similar mutation to a collection of objects. Here’s an example of a simple operation but the block can be as complicated or generic as you need. ints_to_floats = lambda { |i| i.to_f } (0..5).map(&ints_to_floats) #=> [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] The urnary ampersand calls the :symbol’s #to_proc method and passes it as a block…

Lambda’s can come in handy when you need to apply a similar mutation to a collection of objects. Here’s an example of a simple operation but the block can be as complicated or generic as you need. ints_to_floats = lambda { |i| i.to_f } (0..5).map(&ints_to_floats) #=> [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] The urnary ampersand calls the :symbol’s #to_proc method and passes it as a block to the method. In ruby 1.

Read on /2012/03/07/passing-objects-to-methods-as-blocks-in-ruby/

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.