Why this code is working

N

Neeraj Kumar

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' }
 
J

Justin Collins

Neeraj said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,291
Messages
2,571,455
Members
48,132
Latest member
KatlynC08

Latest Threads

Top