JmanxC JmanxC - 1 year ago 37
Ruby Question

Removing an Element in an Array in Ruby(Without using premade methods)

I have the following array


I am now trying to delete an element from the array,lets say a[4]. I know to do this you can use ruby methods such as pop ,however, for this task I am trying to do it manually.

I had tried using the following:

a[4] = nil

However, this just results in the value at this index being replaced by nil instead of removing the pointer to this value completely (ie: a.length still considers nil a value in the array).

As I see there are many questions regarding my question, I will emphasize that what I am trying to do is accomplish the methods such as pop myself. So far all I could come up with is copying all contents of the array to a new array(with 1 less length) and returning that. I am not sure if that is how pop works internally or if there is a better way to do this.

Answer Source


class Array
   def custom_remove(position)
     array = []
     each_with_index do |elm, index|
       next if position == index
       array << elm

1.9.3-p545 :035 > class Array
1.9.3-p545 :036?>          def custom_remove(position)
1.9.3-p545 :037?>              array = []
1.9.3-p545 :038?>              each_with_index do |elm, index|
1.9.3-p545 :039 >                    next if position == index
1.9.3-p545 :040?>                  array << elm
1.9.3-p545 :041?>                end
1.9.3-p545 :042?>              array
1.9.3-p545 :043?>            end
1.9.3-p545 :044?>       end
 => nil
1.9.3-p545 :045 > a = [1,2,3,4,5]
 => [1, 2, 3, 4, 5]
1.9.3-p545 :046 > a.custom_remove(4)
 => [1, 2, 3, 4]