Forum: Ruby Ruby Blocks and C Function Pointers

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A40b277666e008a40ee133256e32d28f?d=identicon&s=25 Terry Cooper (redplastic)
on 2008-12-12 20:09
I'm just starting to learn Ruby and would appreciate a simple practical
explanation of how the functionality of these mechanisms differ.  Many
thanks.
7a561ec0875fcbbe3066ea8fe288ec77?d=identicon&s=25 Sebastian Hungerecker (Guest)
on 2008-12-16 12:56
(Received via mailing list)
Terry Cooper wrote:
> I'm just starting to learn Ruby and would appreciate a simple practical
> explanation of how the functionality of these mechanisms differ.

A function pointer requires a named function to be defined first, which
a) is
a little more to type and b) pollutes the function name space.
Also blocks are closures (i.e. you can access local variables of the
enclosing
scope when inside a block) while functions/methods are not.

HTH,
Sebastian
Cfb541839e42dec39f23a8a4ab8eb762?d=identicon&s=25 Christophe Mckeon (polypus)
on 2008-12-17 19:55
Terry Cooper wrote:
> 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
This topic is locked and can not be replied to.