来自Ruby中的数组的Oneliner关联

时间:2014-06-30 09:56:01

标签: ruby

在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)

但这对我来说似乎太难看了。

2 个答案:

答案 0 :(得分:4)

这应该这样做:

*one, two = [1, 2, 3, 4, 5]
one
# => [1, 2, 3, 4]
two
# => 5

您可以在splatarray 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