Forum: Ruby Why this code is working

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.
Ab13b2178089b79c10d8951c742893bc?d=identicon&s=25 Neeraj Kumar (neerajdotname1)
on 2008-04-18 21:29
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' }
6e366eb5a71be2bad7f383d42aeb4788?d=identicon&s=25 Justin Collins (Guest)
on 2008-04-18 21:43
(Received via mailing list)
Neeraj Kumar wrote:
> 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
851acbab08553d1f7aa3eecad17f6aa9?d=identicon&s=25 Ken Bloom (Guest)
on 2008-04-18 22:13
(Received via mailing list)
On Fri, 18 Apr 2008 14:29:10 -0500, Neeraj Kumar wrote:

> 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
This topic is locked and can not be replied to.