Array.prototype.splice in Ruby
Use 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
First use slice!
to extract the part you want to delete:
a = [1, 2, 3, 4]
ret = a.slice!(2,2)
That leaves [1,2]
in a
and [3,4]
in ret
. Then a simple []=
to insert the new values:
a[2,0] = [:pancakes]
The result is [3,4]
in ret
and [1, 2, :pancakes]
in a
. Generalizing:
def splice(a, start, len, replacements = nil)
r = a.slice!(start, len)
a[start, 0] = replacements if(replacements)
r
end
You could also use *replacements
if you want variadic behavior:
def splice(a, start, len, *replacements)
r = a.slice!(start, len)
a[start, 0] = replacements if(replacements)
r
end