[ACCEPTED]-Array#delete, but return the array?-ruby

Accepted answer
Score: 44

If you want to mutate the original array, like 2 delete, here are options:

ary.reject!{|e| e==42 }.something_else
ary.tap{|a| a.delete 42}.something_else
(ary.delete 42;ary).something_else
(ary-=[42]).something_else

If you want a new array 1 to chain from:

ary.reject{|e| e==42 }.something_else
(ary-[42]).something_else
Score: 5

an_ary.-([el]) looks awful.

What about...

an_ary - [el]

?

The most natural 2 way of dealing with mathematical operations 1 is this...

4 - 2

Not this...

4.-(2)
Score: 4
array.reject{|element| element == value_of_element_to_be_deleted}

0

Score: 1

You can do

my_array.first(n) #1

my_array.last(n) #2

If the elements of the array 2 you want to delete, are at the end (1) or 1 at the beginning (2) of the array.

Score: 1

I had this same question for Array#delete_at that returned 11 an array with the element at a specified 10 index removed, which is why I ended up here. Looks 9 like it isn't built in. In case anyone else 8 is interested, I quickly wrote this monkey 7 patch (I gave this virtually no thought 6 regarding efficiency, and I originally didn't 5 handle any cases such as negative indices 4 or out of bounds indices...but then I decided 3 to quick throw a couple in there):

class Array
  def remove_at(i)
    # handle index out of bounds by returning unchanged array
    return self if i >= self.length

    # remove the i-th element from the end if i is negative
    if i < 0
      i += self.length
      # handle index out of bounds by returning unchanged array
      return self if i < 0
    end

    # Return an array composed of the elements before the specified
    # index plus the elements after the specified index
    return self.first(i) + self.last(self.length - i - 1)
  end
end

test = [0,1,2,3,4,5]
puts test.remove_at(3).inspect
puts test.remove_at(5).inspect
puts test.remove_at(6).inspect
puts test.remove_at(-7).inspect
puts test.remove_at(-2).inspect

I had 2 fun whipping this up, so I figured I might 1 as well post it here :)

Score: 1

I prefer this way:

list = [1, 2, 3, 4, 5]
list.tap { |list| list.delete(2) } # => [1, 3, 4, 5]

0

More Related questions