Reputation: 345
thanks for clicking. I'm learning Ruby from this tutorial.
And here's a bit of code for a method that gives square values.
def first_square_numbers(number_of_squares)
squares = []
idx = 0
while idx < number_of_squares
squares.push(idx * idx)
idx = idx + 1
end
return squares
end
puts("How many square numbers do you want?")
number_of_desired_squares = gets.to_i
squares = first_square_numbers(number_of_desired_squares)
idx = 0
while idx < squares.length
puts(squares[idx])
idx = idx + 1
end
# Output:
# How many square numbers do you want?
# 7
# 0
# 1
# 4
# 9
# 16
# 25
# 36
My question is, in order to print the output, instead of this code:
idx = 0
while idx < squares.length
puts(squares[idx])
idx = idx + 1
end
Can I just put this?
puts(squares)
I tried it and got the same result but I'm not sure which is "more correct" and why.
Thanks!
Upvotes: 0
Views: 897
Reputation: 9508
Yes you should use puts squares
instead (no need for the parentheses here either) because it's more readable and cleaner and well there's no need to re-invent the wheel etc.
Although your overall code works fine, in Ruby it would be better to do something like:
puts "How many squares do you want?"
puts (1..gets.to_i).map {|i| i**2 }
How it works...
Suppose the user enters 7
:
1..gets.to_i #creates a range from 1 to the user's input
#=> 1..7
map {|i| i**2 } #takes each element from 1..7, squares it and puts in an array
#=> [1, 4, 9, 16, 25, 36, 49]
puts #prints out each element of the above array on a new line:
#=>
#1
#4
#9
#16
#25
#36
#49
For further information see documentation for Range and Enumerable#map.
Upvotes: 1
Reputation: 457
puts squares
is, without doubts, more correct since it's an idiomatic Ruby. Another option is to use the each
iterator method:
squares.each { |n| puts n }
But in this case puts
is enough.
Upvotes: 2
Reputation: 14082
If you call puts
with an array, it will print out the elements line by line. The behavior is exactly the same as your loop version.
See the documents here
If called with an array argument, writes each element on a new line.
P.S. It's more practical to use built-in iteration methods to operate on all the elements in an array:
squares.each do |square|
puts(square)
# possibly some other operations on the element
end
Upvotes: 0