Array.prototype.splice in Ruby

A friend asked me Ruby the best and most effective way to achieve the effect of JavaScript splice in Ruby. This means that there is no iteration in the array or copies itself.

"start at the beginning of the index, delete the elements of length and (optionally) insert the elements. Finally return the deleted elements to the array." & L; < This is misleading, see JS example below.

http://www.mennovanslooten.nl/blog/post/41

A quick hack that does not have an optional replacement:

 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 are you? 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 the "b".

+4
source share
2 answers

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] 

Regarding the return of deleted items, []= does not do this ... You can write your own helper method to do this:

 class Array def splice(start, len, *replace) ret = self[start, len] self[start, len] = replace ret end end 
+6
source

Use slice! first slice! to extract the part you want to remove:

 a = [1, 2, 3, 4] ret = a.slice!(2,2) 

This leaves [1,2] in a and [3,4] in ret . Then a simple []= insert new values:

 a[2,0] = [:pancakes] 

The result of [3,4] in ret and [1, 2, :pancakes] in a . Summarizing:

 def splice(a, start, len, replacements = nil) r = a.slice!(start, len) a[start, 0] = replacements if(replacements) r end 

You can also use *replacements if you want variable behavior:

 def splice(a, start, len, *replacements) r = a.slice!(start, len) a[start, 0] = replacements if(replacements) r end 

Patching a monkey and figuring out what you want to do from outside using start and len remains as an exercise.

+2
source

All Articles