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
So the final output would be 9.
Try the following code:
(1..50).each { |n| puts n }
The problem is that you're using []
delimiter instead of ()
one.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With