Your browser (Internet Explorer 6) is out of date. It has known security flaws and may not display all features of this and other websites. Learn how to update your browser.
X

Example using ruby blocks, lambda and Proc

What really distinguishes ruby from other languages is the syntatic sugar of blocks. For example, blocks really come in handy when iterating thru a collection.

The example:

(1..10).collect{|i| i*i}
=> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

But how does the collect method work?

Let’s define an array containing all the prime number up to 100.
Note you will need to be running ruby 1.9.2 to access the Prime class:

require "prime"
prime_numbers = []
Prime.each(100) { |prime| prime_numbers << prime }
 => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Now let’s define our own “change!” method which takes a block, changing the value of each element in our prime_number array object according to the passed block. Note the “bang” or “!” is appended to a method when the behavior is destructive or object altering.

Define our custom method:

class << prime_numbers
  def change!(&b)
    puts "Calling change!"
    self.each_index { |i| self[i] = b.call(self[i]) }
  end
end
 
prime_numbers.change!{|p| p * p}
=> [4, 9, 25, 49, 121, 169, 289, 361, 529, 841, 961, 1369, 1681, 1849, 2209, 2809, 3481, 3721, 4489, 5041, 5329, 6241, 6889, 7921, 9409]

If we want to explicitly create a lambda or proc and pass that along instead:

square = lambda {|x| x * x}
prime_numbers.change!(&square)
=> [4, 9, 25, 49, 121, 169, 289, 361, 529, 841, 961, 1369, 1681, 1849, 2209, 2809, 3481, 3721, 4489, 5041, 5329, 6241, 6889, 7921, 9409]

The “&” operator turns the lambda or Proc object into a block. When “&” is used in the context of a method argument, it creates a Proc object from passed block so the method can now execute the “call” method on the in the block. The “call” method is a method in the “Proc” class.

Leave a comment  

name*

email*

website

Submit comment