ruby 用元素填充数组 N 次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24432225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:31:29  来源:igfitidea点击:

Fill array with element N times

ruby

提问by AME

I want to fill an array with 1 element but 5 times. What I got so far.

我想用 1 个元素填充一个数组,但要填充 5 次。到目前为止我得到了什么。

str = 1234
a = []

5.times { a << str }
puts a # => 1234, 1234, 1234, 1234, 1234

It works but this feels not the ruby way. Can someone point me in the right direction to init an array with 5 times the same value?

它有效,但这感觉不是红宝石的方式。有人可以指出我正确的方向来初始化一个具有 5 倍相同值的数组吗?

回答by sawa

Array.new(5, str)
# => [1234, 1234, 1234, 1234, 1234]

By the way, it is a bad practice to name a variable strthat is assigned the value 1234. It is confusing.

顺便说一下,命名一个str被赋值为的变量是一种不好的做法1234。这令人困惑。

回答by Marek Lipka

This should work:

这应该有效:

[1234] * 5
# => [1234, 1234, 1234, 1234, 1234]

回答by hjing

Although the accepted answer is fine in the case of strings and other immutable objects, I think it's worth expanding on Max's comment about mutable objects.

尽管在字符串和其他不可变对象的情况下接受的答案很好,但我认为值得扩展 Max 关于可变对象的评论。

The following will fill an array of elements with 3 individually instantiated hashes:

以下将用 3 个单独实例化的散列填充元素数组:

different_hashes = Array.new(3) { {} } # => [{}, {}, {}]

The following will fill an array of elements with a reference to the same hash 3 times:

以下将使用对相同散列的引用填充元素数组 3 次:

same_hash = Array.new(3, {}) # => [{}, {}, {}]

If you modify the first element of different_hashes:

如果修改 different_hashes 的第一个元素:

different_hashes.first[:hello] = "world"

Only the first element will be modified.

只会修改第一个元素。

different_hashes # => [{ hello: "world" }, {}, {}]

On the other hand, if you modify the first element of same_hash, all three elements will be modified:

另一方面,如果你修改了 same_hash 的第一个元素,那么三个元素都会被修改:

same_hash.first[:hello] = "world"
same_hash # => [{ hello: "world" }, { hello: "world" }, { hello: "world" }]

which is probably not the intended result.

这可能不是预期的结果。

回答by Alexander Luna

You can fill the array like this:

您可以像这样填充数组:

a = []
=> []

a.fill("_", 0..5)
=> ["_", "_", "_", "_", "_"]