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

爱⌒轻易说出口 提交于 2019-12-30 04:48:05

问题


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 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!


回答1:


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]



回答2:


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

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



来源:https://stackoverflow.com/questions/7665497/ruby-how-to-write-a-bang-method-like-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!