如何使用Ruby在一步中初始化数组?(How to initialize an array in one step using Ruby?)

编程入门 行业动态 更新时间:2024-10-23 23:20:16
如何使用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 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]

更多推荐

本文发布于:2023-08-07 12:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464259.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   初始化   如何使用   Ruby   step

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!