How to initialize an array in one step using Ruby?

后端 未结 9 733
情话喂你
情话喂你 2021-01-30 00:08

I initialize an array this way:

array = Array.new
array << \'1\' << \'2\' << \'3\'

Is it possible to do that in one s

相关标签:
9条回答
  • 2021-01-30 00:19

    To create such an array you could do:

    array = ['1', '2', '3']
    
    0 讨论(0)
  • 2021-01-30 00:20

    To prove There's More Than One Six Ways To Do It:

    plus_1 = 1.method(:+)
    Array.new(3, &plus_1) # => [1, 2, 3]
    

    If 1.method(:+) wasn't possible, you could also do

    plus_1 = Proc.new {|n| n + 1}
    Array.new(3, &plus_1) # => [1, 2, 3]
    

    Sure, it's overkill in this scenario, but if plus_1 was a really long expression, you might want to put it on a separate line from the array creation.

    0 讨论(0)
  • 2021-01-30 00:22

    Oneliner:

    array = [] << 1 << 2 << 3   #this is for fixnums.
    

    or

     a = %w| 1 2 3 4 5 |
    

    or

     a = [*'1'..'3']
    

    or

     a = Array.new(3, '1')
    

    or

     a = Array[*'1'..'3']
    
    0 讨论(0)
  • 2021-01-30 00:24

    Along with the above answers , you can do this too

        =>  [*'1'.."5"]   #remember *
        => ["1", "2", "3", "4", "5"]
    
    0 讨论(0)
  • 2021-01-30 00:25

    You can do

    array = ['1', '2', '3']
    

    As others have noted, you can also initialize an array with %w notation like so:

    array = %w(1 2 3)
    

    or

    array = %w[1 2 3]
    

    Please note that in both cases each element is a string, rather than an integer. So if you want an array whose elements are integers, you should not wrap each element with apostrophes:

    array_of_integers = [1, 2, 3]
    

    Also, you don't need to put comma in between the elements (which is necessary when creating an array without this %w notation). If you do this (which I often did by mistake), as in:

    wrong_array = %w(1, 2, 3)
    

    its elements will be three strings ---- "1,", "2,", "3". So if you do:

    puts wrong_array
    

    the output will be:

    1,
    2,
    3
    =>nil
    

    which is not what we want here.

    Hope this helps to clarify the point!

    0 讨论(0)
  • 2021-01-30 00:32

    You can initialize an array in one step by writing the elements in [] like this:

    array = ['1', '2', '3']
    
    0 讨论(0)
提交回复
热议问题