如何使用Ruby在一步中初始化数组?(How to initialize an array in one step using Ruby?)
我以这种方式初始化数组:
array = Array.new array << '1' << '2' << '3'有可能一步做到吗? 如果是这样,怎么样?
I initialize an array this way:
array = Array.new array << '1' << '2' << '3'Is it possible to do that in one step? If so, how?
最满意答案
正如其他人所说,你可以使用数组文字:
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 }最后,尽管它不会产生与上面其他答案相同的三个字符串数组,但也可以使用Ruby 1.8.7+中的枚举器来创建数组; 例如:
array = 1.step(17,3).to_a #=> [1, 4, 7, 10, 13, 16]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 clarityFor 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]更多推荐
发布评论