问题
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