a = [ 'a' ]
b = [ 'b' ]
def c
return [ 'c' ], [ 'd' ]
end
a, b += c # -> would be awesome, but gives syntax error
a, b = a + c.first, b + c.last # clunky and will call method twice...
# desired result
#
a == [ 'a', 'c' ]
b == [ 'b', 'd' ]
现在我经常发现自己在写:
t, tt = c
a += t
b += tt
但如果你问我,那有点丑陋。
编辑:单元素数组似乎让一些人感到困惑,因为下面的几个答案并没有回答这个问题。我通过让每个数组至少有 2 个元素使它更清楚。
Edit2:我提交了一份 feature request用 ruby 核心实现对解构数组的复合赋值。
最佳答案
a,b = [a+b,c].transpose
#=> [["a", "c"], ["b", "d"]]
a #=> ["a", "c"]
b #=> ["b", "d"]
关于ruby - 是否有 ruby oneliner 可以在没有临时副本的情况下连接嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38428151/