Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print numbers in a range

Tags:

ruby

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

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

but the console print

 [1..50] 

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

like image 377
Alexandre Tavares Avatar asked Jan 25 '13 18:01

Alexandre Tavares


People also ask

What is the output of range 3/15 3?

So the final output would be 9.


2 Answers

Try the following code:

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

The problem is that you're using [] delimiter instead of () one.

like image 138
Glauco Vinicius Avatar answered Sep 21 '22 12:09

Glauco Vinicius


You can use [1..10] with a minor tweak:

[*1..10].each{ |i| p i }

outputs:

1
2
3
4
5
6
7
8
9
10

The * (AKA "splat") "explodes" the range into its components, which are then used to populate the array. It's similar to writing (1..10).to_a.

You can also do:

puts [*1..10]

to print the same thing.

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 output you want.

like image 34
the Tin Man Avatar answered Sep 20 '22 12:09

the Tin Man