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.
“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
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.
Update:
// 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"]
I need the resulting ‘a’ Array, not ‘b’.
Use
Array#[]=.As for returning the removed elements,
[]=doesn’t do that… You could write your own helper method to do it: