在Coffeescript中,我可以这样做:
[one..., two] = [1, 2, 3, 4, 5]
# one = [1, 2, 3, 4]
# two = 5
有没有办法在Ruby中执行此操作(oneliner)?
修改
我知道我可以这样做:
one = [1, 2, 3, 4, 5]
two = one.slice!(-1)
编辑2
Oneliner看起来像这样:
two = (one = [1, 2, 3, 4, 5]).slice!(-1)
但这对我来说似乎太难看了。
答案 0 :(得分:4)
这应该这样做:
*one, two = [1, 2, 3, 4, 5]
one
# => [1, 2, 3, 4]
two
# => 5
您可以在splat
和array destructuring
here
答案 1 :(得分:2)
irb(main):001:0> a = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
irb(main):002:0> *one, two = a
=> [1, 2, 3, 4, 5]
irb(main):003:0> one
=> [1, 2, 3, 4]
irb(main):004:0> two
=> 5