[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: pass block to a method call?

e

1/30/2005 12:34:00 AM

Jeff Davis wrote:
>
>> The only difference is that in the second case the block is anonymous.
>> In the first case, it has a name and so you can pass it around if you
>> want (e.g. recursively).
>>
>>
>>
> That brings up another question: how do you call a function that accepts
> a block if all you have is a proc object?

Prepend the Proc with a &:

def foo()
yield
end

bar = proc { puts 'foo' }

foo bar # Fails
foo &bar # 'foo'

> i.e. what's the difference between the following:
> def foo(&p) p.call; end
> foo { puts 'foo' }
> and:
> def foo(&p) p.call; end
> p = proc { puts 'foo' }
> foo { p.call }
>
> Are those the same? Is the latter the proper way to pass a proc object
> as a block?

See above :)

> Thanks to all for your help. I'm just getting into Ruby and I really
> like it so far (coming from Python/Perl/PHP).
>
> Regards,
> Jeff Davis

E