Ruby中的Array.prototype.splice [英] Array.prototype.splice in Ruby
问题描述
一个朋友问我,使用Ruby的最佳方式来实现Ruby中JavaScript的 splice
方法的效果.这意味着在数组本身或副本上没有迭代.
A friend asked me the Ruby best and performant way to achieve the effect of JavaScript's splice
method in Ruby.
This means no iteration on the Array itself or copies.
从索引开始处开始,删除长度项目并(可选)插入元素.最后将已删除项目返回到数组中."<<这具有误导性,请参见下面的JS示例.
"begin at index start, remove length items and (optionally) insert elements. Finally return the removed items in an array." << This is misleading, see the JS example below.
http://www.mennovanslooten.nl/blog/post/41
没有可选替代项的快速hack:
Quick hack that doesn't have the optional substitution:
from_index = 2
for_elements = 2
sostitute_with = :test
initial_array = [:a, :c, :h, :g, :t, :m]
# expected result: [:a, :c, :test, :t, :m]
initial_array[0..from_index-1] + [sostitute_with] + initial_array[from_index + for_elements..-1]
你是什么人?一行更好.
What's yours? One line is better.
更新:
// JavaScript
var a = ['a', 'c', 'h', 'g', 't', 'm'];
var b = a.splice(2, 2, 'test');
> b is now ["h", "g"]
> a is now ["a", "c", "test", "t", "m"]
我需要生成的'a'数组,而不是'b'.
I need the resulting 'a' Array, not 'b'.
推荐答案
使用 Array#[] =
.
a = [1, 2, 3, 4, 5, 6]
a[2..4] = [:foo, :bar, :baz, :wibble]
a # => [1, 2, :foo, :bar, :baz, :wibble, 6]
# It also supports start/length instead of a range:
a[0, 3] = [:a, :b]
a # => [:a, :b, :bar, :baz, :wibble, 6]
对于返回已删除的元素, [] =
不会执行此操作...您可以编写自己的帮助方法来实现:
As for returning the removed elements, []=
doesn't do that... You could write your own helper method to do it:
class Array
def splice(start, len, *replace)
ret = self[start, len]
self[start, len] = replace
ret
end
end
这篇关于Ruby中的Array.prototype.splice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!