Printing numbers in a range

I am trying to print all numbers between 1 and 50 using the following code:

[1..50].each{|n|   puts n}

      

but console print

 [1..50] 

      

I want to print something like this 1 2 3 4 ... 50

+3


source to share


4 answers


Try using the following code:

(1..50).each { |n| puts n }

      



The problem is you are using a []

separator instead of ()

one.

+12


source


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


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


You can specify a range (in parentheses) in an array ([1 2 3 4 5 6 ... 48 49 50]) and join each element (for example using ' '

if you want all the elements on the same line).

puts (1..50).to_a.join(' ')
# => 1 2 3 4 5 6 7 ... 48 49 50

      

+2


source







All Articles