Add method to an instanced object

后端 未结 8 1744
眼角桃花
眼角桃花 2020-12-08 09:44
obj = SomeObject.new

def obj.new_method
  \"do some things\"
end

puts obj.new_method
> \"do some things\"

This works ok. However, I need to do

8条回答
  •  攒了一身酷
    2020-12-08 09:52

    It's been a long time since I asked this. In ruby 1.9+, there's a better way of doing this by using define_singleton_method, as follows:

    obj = SomeObject.new
    
    obj.define_singleton_method(:new_method) do
      "do some things"
    end
    

提交回复
热议问题