Reputation: 3049
So I am trying to turn a number into an array of integers up to that number starting at one. So for example if the number is 9
I want an array to be nums = [1,2,3,4,5,6,7,8,9]
Is there any built-in method for this? I try the following:
arr = []
(1..9).each do |num|
arr << num
end
But this gives me the following output.
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Upvotes: 0
Views: 108
Reputation: 2675
Use something like this:
(1..x).to_a
Where x
can be any number.
Upvotes: 0
Reputation: 9497
A neat trick:
[*1..9]
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
And as we're in Ruby land, some alternatives:
Array.new 9 { |i| i + 1 }
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
9.times.with_object [] { |i,o| o << i + 1 }
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
(1..Float::INFINITY).take 9
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
Upvotes: 2
Reputation: 1434
num = 9
(1..num).to_a
# => [1, 2, 3, 4, 5, 6, 7, 8, 9]
or
Array(1..num)
Upvotes: 2
Reputation: 5213
Using the ..
operator creates a Range, and Per the docs, a Range, like any other Enumerable object, can be converted directly into an Array:
(1..9).to_a
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
You might be interested to know that you can also do this with a Range built using String values:
('a'..'e').to_a
#=> ["a", "b", "c", "d", "e"]
Upvotes: 4