2 Replies - 671 Views - Last Post: 16 May 2013 - 07:20 PM Rate Topic: -----

#1 Btu  Icon User is offline

  • D.I.C Regular

Reputation: 36
  • View blog
  • Posts: 250
  • Joined: 16-May 11

Method using code blocks

Posted 16 May 2013 - 03:25 PM

I have a range here, and I'm calling the "each" method, passing each number to the code block, and outputting it
(IRB)

(1..10).each{|n| puts "#{n}"}



and outputs 1-10 and => 1..10 as expected.

What I don't understand is, when you have a second parameter like this:

(1..10).each{|n, i| puts "#{n}, #{i}"}




What is the second parameter?
I can see that it's nil for each iteration, but why can we do this?

Sorry if this is a newbie question, I'm just starting out with Ruby.

Thanks in advance!

Is This A Good Question/Topic? 1
  • +

Replies To: Method using code blocks

#2 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3354
  • View blog
  • Posts: 11,352
  • Joined: 12-December 12

Re: Method using code blocks

Posted 16 May 2013 - 03:58 PM

I don't know myself why it doesn't generate an error - it seems that Ruby ignores the unpopulated parameter. Whereas with each_with_index the second parameter is populated with index numbers:

s = ['str1', 'str2', 'strx']

s.each_with_index{|n, i| puts "#{n}, #{i}"}

# Output:
# str1, 0
# str2, 1
# strx, 2


Yes, Ruby just ignores any un-used parameters:

(1..10).each{|n, i, j| puts "#{n}, #{i}, #{j}"}

doesn't generate an error.

This post has been edited by andrewsw: 16 May 2013 - 03:54 PM

Was This Post Helpful? 2
  • +
  • -

#3 Btu  Icon User is offline

  • D.I.C Regular

Reputation: 36
  • View blog
  • Posts: 250
  • Joined: 16-May 11

Re: Method using code blocks

Posted 16 May 2013 - 07:20 PM

Thanks for the explanation and example!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1