开发者

Ruby: How to write a bang method, like map?

I'd like to write some new Array methods that alter the calling object, like so:

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

...but I'm blanking on how to do this. I 开发者_Python百科think I need a new brain.

So, I'd like something like this:

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

map! is just an example, I'd like to write a completely fresh one without using any pre-existing ! methods.

Thanks!


EDIT - Updated answer to reflect the changes to your question.

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

foo = [1,2,3,4]

foo.stuff!

p foo #=> ['a',2,3,4]


def stuff!
  self.something = 'something else'
end

bam, you've modified the underlying object without returning a new object

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜