Correct way to populate an Array with a Range in Ruby

前端 未结 6 588
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:19

    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]
    

提交回复
热议问题