18

Ruby 2.4. I want to create a new array by removing an element at a specified index from an array. I thought delete_at was the way, but it performs in-place and doesn't return the newly created array, but rather, the element that was removed:

2.4.0 :003 > a = ["a", "b", "c"] => ["a", "b", "c"] 2.4.0 :004 > a.delete_at(0) => "a" 2.4.0 :005 > a => ["b", "c"] 

How do I delete an element from an array at a specified index but not perform the operation in place?

2 Answers 2

22

You can duplicate array and remove element from this duplicate. Use tap to return array, but not a deleted element.

2.3.3 :018 > a = ["a", "b", "c"] => ["a", "b", "c"] 2.3.3 :019 > b = a.dup.tap{|i| i.delete_at(0)} => ["b", "c"] 2.3.3 :020 > b => ["b", "c"] 

Another way is to use reject with with_index:

2.3.3 :042 > b = a.reject.with_index{|v, i| i == 0 } => ["b", "c"] 2.3.3 :043 > b => ["b", "c"] 
Sign up to request clarification or add additional context in comments.

Comments

1

You wish to create a new array which is the same as a given array less the element at a given index.

You could use Array#[] (aka Array#slice) and Array#concat.

def copy_wo_element(arr, index_to_exclude) arr[0,index_to_exclude].concat(arr[index_to_exclude+1..-1]) end arr = [1,2,3,4,5] copy_wo_element(arr, 0) #=> [2, 3, 4, 5] copy_wo_element(arr, 1) #=> [1, 3, 4, 5] copy_wo_element(arr, 2) #=> [1, 2, 4, 5] copy_wo_element(arr, 3) #=> [1, 2, 3, 5] copy_wo_element(arr, 4) #=> [1, 2, 3, 4] 

You could instead write

arr[0,index_to_exclude] + arr[index_to_exclude+1..-1] 

but the use of concat avoids the creation of the temporary array arr[index_to_exclude+1..-1].

Comments