Terry said:
I'm just starting to learn Ruby and would appreciate a simple practical
explanation of how the functionality of these mechanisms differ. Many
thanks.
they are very different.
first off strictly speaking, a block in ruby is not
a first class object. i suspect you may actually be
asking about procs or lambdas. in the following code
the block acts as a kind of extension to the method
but you notice that you have no references to it and
the ruby interpreter is free to treat it internally
however it likes.
10.times do |x|
...
end
if you do something like this however to 'capture' the block:
p = lambda do |x|
...
end
now you have a full blown object p whereas in C you
would only have a pointer to some code. p defines methods
like any other object, and as sebastian noted p is also a closure
and can capture lexically enclosing state, which is actually
a very powerful feature:
make_counter = lambda do |start|
lambda do
start += 1
end
end
c = make_counter[7]
puts c.class
3.times { puts c.call }
notice also that one lambda is building and returning another,
which in C, where functions are not first class, that is impossible
to do.
hth,
_c