Printing numbers in a range
4 answers
The error here is that you are creating an Array object with a range as the only element.
> [1..10].size
=> 1
If you want to call methods of a type each
on a range, you must wrap the range in parentheses to avoid calling the method on the last element of the range and not on the range itself.
=> (1..10).each { |i| print i }
12345678910
Other ways to achieve this:
(1..50).each { |n| print n }
1.up_to(50) { |n| print n }
50.times { |n| print n }
+6
source to share
You can use [1..10]
with minor tweak:
[*1..10].each{ |i| p i }
outputs:
1 2 3 4 five 6 7 8 nine ten
*
(AKA "splat") "explodes" a range into its components, which are then used to populate the array. It looks like a recording (1..10).to_a
.
You can also do:
puts [*1..10]
to print the same.
So try:
[*1..10].join(' ') # => "1 2 3 4 5 6 7 8 9 10"
or
[*1..10] * ' ' # => "1 2 3 4 5 6 7 8 9 10"
To get the desired result.
+5
source to share