Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Loops Ruby Iteration Times Iteration

Mark Weinberg
Mark Weinberg
3,002 Points

How does Ruby know from the word "item" in the pipe to print out "Hello!" and then the numbers 0 to 5?

Regarding this code:

5.times do |item|
  puts "Hello! #{item}"
end

How does Ruby know from the word "item" to count 0 to 5 after each Hello!?

I can put in a different word like "dog" in the pipe argument, put "dog" in the string interpolation and still the same results. Can someone explain to me what the argument in the pipe is supposed to do?

2 Answers

Jordan Bowman
Jordan Bowman
9,439 Points

You're right, |item| can be named anything you want: dog, x, i, mark, whatever.

It's purpose is to represent each piece/item/element that you are iterating over. If you're iterating over an array, it represents each item in that array.

Then, you can then use this representative keyword inside the block to work with each item you're iterating over. In your example, you wouldn't be able to print to the screen "Hello [name of item being iterated over]" without having this representative keyword available to you.

So in short, you can name this representation whatever you want, and then you can use that to work with each iterated item and do whatever you want with it inside the block.

Todd MacIntyre
Todd MacIntyre
12,248 Points

If nothing is being passed INTO the argument, then it will default to the indexes of each iteration.