Quote:
Originally Posted by CoderMan
I was reading about Ruby code blocks, but it's all a bit hazy.
My questions:
1. Can you store executable code in the value part of a hash (err...
associative array)
2. If you did, how would you call the code?
3. If you executed this stored code, would it be possible when doing so
to pass in an object to the code that it could use?
I would appreciate any simple examples.
|
As usual, figured it out on my own first.
This seems to work:
Code:
$ cat proc.rb
class Interf
def increment(n)
n+1
end
end
interf = Interf.new
proc = Proc.new {|obj| puts obj.increment(12).to_s}
proc2 = Proc.new {|obj| puts obj.increment(14).to_s}
hash = {'Bob' => proc,
'Frank' => proc2
}
hash['Bob'].call(interf)
hash['Frank'].call(interf)
$ ruby proc.rb
13
15