Correct way to populate an Array with a Range in Ruby

RubySyntax

Ruby Problem Overview


I am working through a book which gives examples of Ranges being converted to equivalent arrays using their "to_a" methods

When i run the code in irb I get the following warning

 warning: default `to_a' will be obsolete

What is the the correct alternative to using to_a?

are there alternate ways to populate an array with a Range?

Ruby Solutions


Solution 1 - 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]

Solution 2 - Ruby

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 obsolete
ArgumentError: bad value for range
        from (irb):1

So perhaps you are missing the parentheses?

(I am running Ruby 1.8.6 patchlevel 114)

Solution 3 - Ruby

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

Solution 4 - Ruby

Check this:

a = [*(1..10), :top, *10.downto( 1 )]

Solution 5 - Ruby

This is another way:

irb> [*1..10]

=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Solution 6 - Ruby

I just tried to use ranges from bigger to smaller amount and got the result I didn't expect:

irb(main):007:0> Array(1..5)
=> [1, 2, 3, 4, 5]
irb(main):008:0> Array(5..1)
=> []

That's because of ranges implementations.
So I had to use the following option:

(1..5).to_a.reverse

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWillbillView Question on Stackoverflow
Solution 1 - RubyZamithView Answer on Stackoverflow
Solution 2 - RubyDaniel LucraftView Answer on Stackoverflow
Solution 3 - RubyRichard TurnerView Answer on Stackoverflow
Solution 4 - RubyBoris StitnickyView Answer on Stackoverflow
Solution 5 - RubyJesús Andrés Valencia MontoyaView Answer on Stackoverflow
Solution 6 - RubyNickolay KondratenkoView Answer on Stackoverflow