arraysrubyelement

How do I remove an element from an array at a specified index but not do the operation in-place


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?


Solution

  • 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"]