是否有提供Array#first
和Array#last
破坏性版本的库?如果没有,实施它们的最有效方法是什么?像这样:
a = [:a, :b, :c, :d, :e]
a.first!(2) # => [:a, :b]
a # => [:c, :d, :e]
a.last!(1) # => [:e]
a # => [:c, :d]
答案 0 :(得分:6)
您在寻找Array#shift
和Array#pop
吗?
答案 1 :(得分:2)
您还可以尝试Array#slice!
方法,如下所示:
p RUBY_VERSION
a = [1,2,3,4,5]
a.slice!(0)
p a
a = [1,2,3,4,5]
a.slice!(0,2)
p a
a = [1,2,3,4,5]
a.slice!(-1)
p a
a = [1,2,3,4,5]
a.slice!(-3,3)
p a
输出:
"2.0.0"
[2, 3, 4, 5]
[3, 4, 5]
[1, 2, 3, 4]
[1, 2]