[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Ruby Blocks and C Function Pointers

Terry Cooper

12/12/2008 7:03:00 PM

I'm just starting to learn Ruby and would appreciate a simple practical
explanation of how the functionality of these mechanisms differ. Many
thanks.
--
Posted via http://www.ruby-....

2 Answers

Sebastian Hungerecker

12/16/2008 11:47:00 AM

0

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
--
Jabber: sepp2k@jabber.org
ICQ: 205544826

Christophe Mckeon

12/17/2008 6:48:00 PM

0

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




--
Posted via http://www.ruby-....