内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我以这种方式初始化了一个数组:
array = Array.new array << '1' << '2' << '3'
一步就能做到吗?如果是,怎么做?
正如其他人所指出的,可以使用数组文字:
array = [ '1', '2', '3' ]
还可以使用范围:
array = ('1'..'3').to_a # parentheses are required # or array = *('1'..'3') # parentheses not required, but included for clarity
对于许多空格分隔字符串的数组,最简单的是:
array = %w[ 1 2 3 ]
也可以将一个块传递给Array.new,并使用它来确定每个条目的值:
array = Array.new(3){ |i| (i+1).to_s }
最后,尽管它不会产生与上面的其他答案相同的三个字符串数组,但是也要注意,可以在Ruby1.8.7+中使用枚举数来创建数组;例如:
array = 1.step(17,3).to_a #=> [1, 4, 7, 10, 13, 16]
array = [] << 1 << 2 << 3 #this is for fixnums.
或
a = %w| 1 2 3 4 5 |
或
a = [*'1'..'3']
或
a = Array.new(3, '1')
或
a = Array[*'1'..'3']