Ruby: Calling class method from instance

后端 未结 9 2230
谎友^
谎友^ 2021-01-29 17:26

In Ruby, how do you call a class method from one of that class\'s instances? Say I have

class Truck
  def self.default_make
    # Class method.
    \"mac\"
  end         


        
9条回答
  •  不要未来只要你来
    2021-01-29 18:25

    Here's an approach on how you might implement a _class method that works as self.class for this situation. Note: Do not use this in production code, this is for interest-sake :)

    From: Can you eval code in the context of a caller in Ruby? and also http://rubychallenger.blogspot.com.au/2011/07/caller-binding.html

    # Rabid monkey-patch for Object
    require 'continuation' if RUBY_VERSION >= '1.9.0'
    class Object
      def __; eval 'self.class', caller_binding; end
      alias :_class :__
      def caller_binding
        cc = nil; count = 0
        set_trace_func lambda { |event, file, lineno, id, binding, klass|
          if count == 2
            set_trace_func nil
            cc.call binding
          elsif event == "return"
            count += 1
          end
        }
        return callcc { |cont| cc = cont }
      end
    end
    
    # Now we have awesome
    def Tiger
      def roar
        # self.class.roar
        __.roar
        # or, even
        _class.roar
      end
      def self.roar
        # TODO: tigerness
      end
    end
    

    Maybe the right answer is to submit a patch for Ruby :)

提交回复
热议问题