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,247 Points

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