如何使用Ruby一步初始化数组?

use*_*052 98 ruby arrays initialization

我这样初始化一个数组:

array = Array.new
array << '1' << '2' << '3'
Run Code Online (Sandbox Code Playgroud)

是否有可能一步到位?如果是这样,怎么样?

Phr*_*ogz 183

您可以使用数组文字:

array = [ '1', '2', '3' ]
Run Code Online (Sandbox Code Playgroud)

您还可以使用范围:

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

对于以空格分隔的字符串数组,可以使用Percent String语法:

array = %w[ 1 2 3 ]
Run Code Online (Sandbox Code Playgroud)

您还可以传递一个块来Array.new确定每个条目的值是什么:

array = Array.new(3) { |i| (i+1).to_s }
Run Code Online (Sandbox Code Playgroud)

最后,虽然它不会产生与上面其他答案相同的三个字符串数组,但请注意,您可以使用Ruby 1.8.7+中的枚举器来创建数组; 例如:

array = 1.step(17,3).to_a
#=> [1, 4, 7, 10, 13, 16]
Run Code Online (Sandbox Code Playgroud)

  • 加上一个详细的答案,即使我更喜欢splat over`to_a`(`[*'1'..'3']`). (4认同)
  • 此外,可以使用类方法Array :: []:`Array ["1","2","3"]#=> ["1","2","3"]`(我不是我认为这个方法与数组文字构造函数有关.你也可以使用顶级的Kernel#Array(方法名看起来像一个类名)`Array(1..5)#=> [1,2,3,4,5]` (2认同)

pan*_*rey 18

Oneliner:

array = [] << 1 << 2 << 3   #this is for fixnums.
Run Code Online (Sandbox Code Playgroud)

要么

 a = %w| 1 2 3 4 5 |
Run Code Online (Sandbox Code Playgroud)

要么

 a = [*'1'..'3']
Run Code Online (Sandbox Code Playgroud)

要么

 a = Array.new(3, '1')
Run Code Online (Sandbox Code Playgroud)

要么

 a = Array[*'1'..'3']
Run Code Online (Sandbox Code Playgroud)

  • 我没有投票,但我猜测是因为这调用了三个方法并逐步增长数组,而不是`[1,2,3]`进行单次初始化.而且,你的角色更多.此外,您已经创建了一个Fixnums数组,而OP则询问了一个字符串数组. (8认同)

Ram*_*Vel 8

除了上述答案,您也可以这样做

    =>  [*'1'.."5"]   #remember *
    => ["1", "2", "3", "4", "5"]
Run Code Online (Sandbox Code Playgroud)


And*_*imm 7

为了证明有不止一个六法做到这一点:

plus_1 = 1.method(:+)
Array.new(3, &plus_1) # => [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

如果1.method(:+)不可能,你也可以这样做

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

当然,在这种情况下它太过分了,但如果plus_1是一个很长的表达式,你可能想把它放在与数组创建不同的一行上.