01-13-2010, 08:24 PM
In Ruby, you get a number of different ways of storing code in a object form, but here we're going to look at the proc objects. The class proc is used to wrap up ruby blocks as an object. Proc objects still carry around the context in the way it was defined just like normal blocks do.
Proc objects are also automatically created when a method is defined with a trailing & parameter is called with the block.
The out put of this snippet is shown here:
You can pass proc objects to methods that are expecting a block:
There is a couple of ways of storing blocks of code into proc objects. This might come in handy some day
- Wolskie
Code:
newproc = Proc.new { |input| puts "Input is #{input}" }
newproc.call(9001) # Input is 9001
Proc objects are also automatically created when a method is defined with a trailing & parameter is called with the block.
Code:
def we_take_a_block(x, &a_block)
puts a_block.class
x.times {|input| a_block.call(input, input*input) }
end
we_take_a_block(5) { |a, b| puts "#{a} squared equals #{b}" }
The out put of this snippet is shown here:
Code:
Proc
0 squared equals 0
1 squared equals 1
2 squared equals 4
3 squared equals 9
4 squared equals 16
You can pass proc objects to methods that are expecting a block:
Code:
proc2 = proc { |qwerty|, print qwerty, " AND " }
("A".."C").each(&proc2) #A AND B AND C
There is a couple of ways of storing blocks of code into proc objects. This might come in handy some day
- Wolskie