Thread Rating:
  • 2 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tutorial] Storing Code As Objects
#1
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.

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 Tongue

- Wolskie
Reply
#2
Great tutorial from the one and only, who made rPort, rbShell and Sector Sweep. This man here is a god amongst programming, and the Co-Admin of Pyrite Design.

Welcome to the Support Forums, bro. And nais tutorial! Big Grin
At the top will be the same place you hang from.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)