Search code examples
arraysrubyyield

Modifying Array instances self with external Array method


While practicing ruby, I wrote a class such like that:

class Array

  def my_each
    c = 0
    until c == size
      yield self[c]
      c += 1
    end
  end

  def my_map
    c = 0
    acc = []
    my_each {|e| acc << yield(e)}
    acc
  end

end

def plus_two(a)
  a += 2
end

nums = [1, 2, 3, 4, 5]
nums.my_map {|e| plus_two(e)}

p nums

It works great and expected. However, I want to implement the Array#my_map! which modifies the instance and I could not figure out how to modify the existing array in that way.

As far as I know (I'm a beginner Ruby developer has experience on Java) we can access the instance variables by @ but in that case, I could not figure out the best practice. What's the decent way to solve scenarios like that?

Thanks.


Solution

  • I've added a Array#my_map! method like in the below:

      def my_map!
        self.replace(my_map {|e| yield(e)})
      end
    

    So we need to replace the instance (self) with our new temporary instance. Works well.