Rodrigo E. Rodrigo E. - 7 months ago 11
Ruby Question

Range is printed at the end of the "each" iteration

What I'll show is a fulish function, but it's only to explain my problem in a simple way. If I solve the problem in this function, I solved the problem in the original code too.

The problem is simple, and probably the solution too, but I'm new in Ruby and have this doubt. I want to print the values in a range:

def test
(0...5).each do |i|
puts i
end
end


When I call the function, the result that I want is

0
1
2
3
4


but the result that I have is

0
1
2
3
4
0...5


Why this
0...5
is printed together? How can I avoid that?

Answer

i don't think the 0..5 is being produced as part of the puts call. Rather, when you call this in your REPL (irb, pry, rails console, etc), you're seeing because it's the last returned value in your code.

Let me show you an example.

Say I save a file called test.rb with the following content:

1.upto(5).each { |i| puts i }

If I call ruby test.rb, I see the expected output,

0
1
2
3
4

If I open irb and run require("./test.rb"), I see the same output.

It's only when I paste the code into irb that I see the additional output (=> 0...5). So I would just ignore this.