# Why this code is working

**URL:** <https://www.ruby-forum.com/t/why-this-code-is-working/135178>\
**Category:** Ruby\
**Created:** [April 18, 2008, 9:29pm UTC](https://www.ruby-forum.com/t/why-this-code-is-working/135178 "2008-04-18T21:29:09Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![nekapoor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/ea666f/32.png) [@nekapoor](https://www.ruby-forum.com/u/nekapoor)\
**Post date:** [April 18, 2008, 9:29pm UTC](https://www.ruby-forum.com/t/why-this-code-is-working/135178/1 "2008-04-18T21:29:09Z")

</div>

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’ }

---

<div class="post-metadata">

**Author:** ![nekapoor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/ea666f/32.png) [@nekapoor](https://www.ruby-forum.com/u/nekapoor)\
**Post date:** [April 18, 2008, 9:43pm UTC](https://www.ruby-forum.com/t/why-this-code-is-working/135178/2 "2008-04-18T21:43:10Z")

</div>

Neeraj K. 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

---

<div class="post-metadata">

**Author:** ![nekapoor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/ea666f/32.png) [@nekapoor](https://www.ruby-forum.com/u/nekapoor)\
**Post date:** [April 18, 2008, 10:13pm UTC](https://www.ruby-forum.com/t/why-this-code-is-working/135178/3 "2008-04-18T22:13:54Z")

</div>

On Fri, 18 Apr 2008 14:29:10 -0500, Neeraj K. 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
