Ruby: How to write a hacking method, for example, a map?

I would like to write some new Array methods that modify the calling object, for example:

a = [1,2,3,4]
a.map!{|e| e+1}
a = [2,3,4,5]

... but I'm talking about how to do it. I think I need a new brain.

So, I would like something like this:

class Array
  def stuff!
    # change the calling object in some way
  end
end

map! this is just an example, I would like to write a completely new one without using the pre-existing ones! Methods

Thank!

+5
source share
2 answers

EDIT - Updated answer to reflect changes in your question.

class Array
  def stuff!
        self[0] = "a"
  end
end

foo = [1,2,3,4]

foo.stuff!

p foo #=> ['a',2,3,4]
+7
source
def stuff!
  self.something = 'something else'
end

bam, you changed the base object without returning a new object

+1
source

All Articles