How to initialize an array in one step using Ruby?

后端 未结 9 735
情话喂你
情话喂你 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:33

    You can use an array literal:

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

    You can also use a range:

    array = ('1'..'3').to_a  # parentheses are required
    # or
    array = *('1'..'3')      # parentheses not required, but included for clarity
    

    For arrays of whitespace-delimited strings, you can use Percent String syntax:

    array = %w[ 1 2 3 ]
    

    You can also pass a block to Array.new to determine what the value for each entry will be:

    array = Array.new(3) { |i| (i+1).to_s }
    

    Finally, although it doesn't produce the same array of three strings as the other answers above, note also that you can use enumerators in Ruby 1.8.7+ to create arrays; for example:

    array = 1.step(17,3).to_a
    #=> [1, 4, 7, 10, 13, 16]
    
    0 讨论(0)
  • 2021-01-30 00:34

    You can simply do this with %w notation in ruby arrays.

    array = %w(1 2 3)
    

    It will add the array values 1,2,3 to the arrayand print out the output as ["1", "2", "3"]

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

    If you have an Array of strings, you can also initialize it like this:

    array = %w{1 2 3}

    just separate each element with any whitespace

    0 讨论(0)
提交回复
热议问题