如何使用Ruby一步一步初始化数组? [英] How to initialize an array in one step using Ruby?

查看:135
本文介绍了如何使用Ruby一步一步初始化数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以这种方式初始化数组:

I initialize an array this way:

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

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

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

array = %w[ 1 2 3 ]

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

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 }

最后,尽管它不能产生与上述其他答案相同的三个字符串数组,但是还要注意,您可以在Ruby 1.8.7+中使用枚举器创建数组;例如:

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]

这篇关于如何使用Ruby一步一步初始化数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆