Correct way to populate an Array with a Range in Ruby Correct way to populate an Array with a Range in Ruby ruby ruby

Correct way to populate an Array with a Range in Ruby


You can create an array with a range using splat,

>> a=*(1..10)=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

using Kernel Array method,

Array (1..10)=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

or using to_a

(1..10).to_a=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


This works for me in irb:

irb> (1..4).to_a=> [1, 2, 3, 4]

I notice that:

irb> 1..4.to_a(irb):1: warning: default `to_a' will be obsoleteArgumentError: bad value for range        from (irb):1

So perhaps you are missing the parentheses?

(I am running Ruby 1.8.6 patchlevel 114)


Sounds like you're doing this:

0..10.to_a

The warning is from Fixnum#to_a, not from Range#to_a. Try this instead:

(0..10).to_a