Correct way to populate an Array with a Range in Ruby

前端 未结 6 589
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]
    
    0 讨论(0)
  • 2020-12-04 06:19

    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)

    0 讨论(0)
  • 2020-12-04 06:24

    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
    
    0 讨论(0)
  • 2020-12-04 06:27

    Check this:

    a = [*(1..10), :top, *10.downto( 1 )]
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-04 06:31

    This is another way:

    irb> [*1..10]
    
    => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    0 讨论(0)
提交回复
热议问题