Add method to an instanced object

后端 未结 8 1762
眼角桃花
眼角桃花 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 10:08

    You can use modules.

    module ObjSingletonMethods
      def new_method
        "do some things"
      end
    end
    
    
    obj.extend ObjSingletonMethods
    
    puts obj.new_method # => do some things
    

    Now if you need to add more methods to that object, you just need to implement the methods in the module and you are done.

提交回复
热议问题