Correct way to populate an Array with a Range in Ruby

前端 未结 6 610
Happy的楠姐
Happy的楠姐 2020-12-04 05:50

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 fol

6条回答
  •  余生分开走
    2020-12-04 06:30

    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
    

提交回复
热议问题