简体   繁体   中英

Ruby Range printing out extra

I'm new to coding so please free to point out any errors in the way I refer to code.

rows = 5
 (1..rows).each do |n|
  print n, ' '
end

This prints out what I expect it to: 1 2 3 4 5 .

But, when I put it into a method:

def test(rows)
  (1..rows).each do |n|
   print n, ' '
 end
end

puts test(5)

I get 1 2 3 4 5 1..5 .

Why does the 1..5 show up? And how do I get rid of it?

I need it in the method because I plan to add more code to it.

each on a Range returns the range after the looping is done, and you're probably printing the return value of test too.

Just run test(5) instead of puts test(5) or something.

Ruby always returns the last line of any function.

You are executing puts test(5) , and test(5) prints the data you expect, and the extra puts prints out the data returned by test(5) method.

Hope that answers your question.

The final 1..5 is the return value from the script. You get that when you run the code in IRB. When you run that as a standalone Ruby script, it will not show up, so you do not need to worry about it.

A Ruby function will return the last statement, in your case 1..5 . To illustrate I'll give it a different return value:

def test(rows)
  (1..rows).each {|n| puts "#{ n } "}
  return 'mashbash'
end

# Just the function invokation, only the function will print something
test(5) # => "1 2 3 4 5 "

# Same as above, plus printing the return value of test(5)
puts test(5) # => "1 2 3 4 5 mashbash"

You could write your example a little differently to achieve what you like:

def second_test(rows)
  # Cast range to an array
  array = (1..rows).to_a # [1, 2, 3, 4, 5]
  array.join(', ') # "1, 2, 3, 4, 5", and it is the last statement => return value
end

# Print the return value ("1, 2, 3, 4, 5") from the second_test function
p second_test(5) 
# => "1, 2, 3, 4, 5"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM