1 storing the code like an object
When you want to store a piece of code in the form of an object, Ruby gives you several methods. Here we'll introduce the Proc object, the method object, and the Unboundmethod object.
The built-in proc class wraps Ruby block to an object. A Proc object, like a blocks, is a closure and preserves the context in which it is defined:
Ruby Code
MyProc = proc.new {|a| puts "Param is #{a}"}
Myproc.call (?) # Param is 99
The Proc object is created automatically when a method accepts a & parameter, and then the method is invoked immediately after a block is called:
Ruby Code
def take_block (x, &block)
puts Block.class
x.times {|i| block[i, I*i]}
end
take_block (3) { |n,s| Puts "#{n} squared is #{s}"}
Note here that the [] method is an alias to the call method.
If you have a Proc object, you can pass it to a method that can receive blocks. Just add & in front of it.
Ruby Code
MyProc = proc {|n| print n, "... "}
(1..3). each (&myproc) # 1 ... 2.. 3...