是否有提供破坏性版本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]
您在寻找Array#shift
和Array#pop
吗?
您也可以尝试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]