I'm new at Ruby, and failing to Google this easy question:
What's the normal way to obtain a list of numbers [1, 2, ..., n]
in Ruby? In Haskell I just type [1..n]
, and I'm sure that this is easy in Ruby also, but I can't guess it.
I'm new at Ruby, and failing to Google this easy question:
What's the normal way to obtain a list of numbers [1, 2, ..., n]
in Ruby? In Haskell I just type [1..n]
, and I'm sure that this is easy in Ruby also, but I can't guess it.
1..n
is a Range in Ruby. You can convert it to an array using (1..n).to_a
or the shorter form [*1..n]
.
Depending on what you're doing, using the Range directly might be more efficient.
Ruby has special range objects, written as 1..10
or whatever. For many purposes you can use one of these instead of an array. If you need the array, call the range object's to_a
method:
(1..10).to_a
You mean a range? You can do it like this:
(0..n)
This will give you an array that has the numbers 0 to 9 in it.
For more information about ranges and arrays, visit here: http://www.ruby-doc.org/core/classes/Range.html
Another approach is
1.upto(9).to_a
Pretty boring by itself, but you can also do
1.step(10, 3).to_a #=> [1, 4, 7, 10]