在 Ruby 中创建或附加到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12163625/
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
Create or append to array in Ruby
提问by amindfv
foo ||= []
foo << :element
Feels a little clunky. Is there a more idiomatic way?
感觉有点笨重。有没有更惯用的方式?
回答by Dave Newton
(foo ||= []) << :element
But meh. Is it really so onerous to keep it readable?
但是嗯。保持可读性真的那么繁重吗?
回答by meub
You can always use the push method on any array too. I like it better.
你也可以在任何数组上使用 push 方法。我更喜欢它。
(a ||= []).push(:element)
回答by Christian Rolle
You also could benefit from the Kernel#Array, like:
您还可以从Kernel#Array 中受益,例如:
# foo = nil
foo = Array(foo).push(:element)
# => [:element]
which has the benefit of flattening a potential Array, like:
它具有展平潜在数组的好处,例如:
# foo = [1]
foo = Array(foo).push(:element)
# => [1, :element]

