[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Why this code is working

Neeraj Kumar

4/18/2008 7:29:00 PM


this code is a simplified version of the code I saw in Rails.

def speak(*types,&block)
block.call
end

# I can understand why this code is working
speak(23) { puts 'hi' }

# why this code is working ?. This code should fail because I am not
providing any # param to types. It means block is being passed as the
first param and that's not # good
speak { puts 'hi' }
--
Posted via http://www.ruby-....

2 Answers

Justin Collins

4/18/2008 7:43:00 PM

0

Neeraj Kumar wrote:
> this code is a simplified version of the code I saw in Rails.
>
> def speak(*types,&block)
> block.call
> end
>
> # I can understand why this code is working
> speak(23) { puts 'hi' }
>
> # why this code is working ?. This code should fail because I am not
> providing any # param to types. It means block is being passed as the
> first param and that's not # good
> speak { puts 'hi' }
>
*args means "zero or more parameters" which are then placed in an array
and passed into the method. The block is not being passed as the first
parameter.

-Justin

Ken Bloom

4/18/2008 8:08:00 PM

0

On Fri, 18 Apr 2008 14:29:10 -0500, Neeraj Kumar wrote:

> this code is a simplified version of the code I saw in Rails.
>
> def speak(*types,&block)
> block.call
> end
>
> # I can understand why this code is working speak(23) { puts 'hi' }
>
> # why this code is working ?. This code should fail because I am not
> providing any # param to types. It means block is being passed as the
> first param and that's not # good
> speak { puts 'hi' }

When you prefix the last argument name with a * (as you did with *types)
then you can have any number of arguments (0 or more) at the end, and
they will all be put into an array.

so

def speak(*types,&block)
p types
block.call
end

speak(23) { puts 'hi' }
speak { puts 'hi' }

will print

[23]
hi
[]
hi




--
Ken (Chanoch) Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology.
http://www.iit.edu...