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

编程入门 行业动态 更新时间:2024-10-24 01:56:44
本文介绍了如何使用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一步一步初始化数组?

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

发布评论

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

>www.elefans.com

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