Add method to an instanced object

后端 未结 8 1741
眼角桃花
眼角桃花 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:00
    class Some
    end 
    
    obj = Some.new
    
    class << obj
      def hello 
        puts 'hello'
      end 
    end 
    
    obj.hello
    
    obj2 = Some.new
    obj2.hello # error
    

    Syntax class << obj means that we are opening definition of the class for an object. As you probably know we can define Ruby class methods using syntax like this:

    class Math
    
        class << self 
    
            def cos(x)
                ...
            end 
    
            def sin(x)
                ...
            end 
        end 
    end 
    

    Then we can use those methods like this:

    Math.cos(1)
    

    In Ruby, everything is an object - even classes. self here is an object of Math class itself (you can access that object with Math.class). So syntax class << self means we are opening class for Math class object. Yes, it means that Math class has class too (Math.class.class).

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题