Ruby: Calling class method from instance

后端 未结 9 2051
谎友^
谎友^ 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:00

    If you have access to the delegate method you can do this:

    [20] pry(main)> class Foo
    [20] pry(main)*   def self.bar
    [20] pry(main)*     "foo bar"
    [20] pry(main)*   end  
    [20] pry(main)*   delegate :bar, to: 'self.class'
    [20] pry(main)* end  
    => [:bar]
    [21] pry(main)> Foo.new.bar
    => "foo bar"
    [22] pry(main)> Foo.bar
    => "foo bar"
    

    Alternatively, and probably cleaner if you have more then a method or two you want to delegate to class & instance:

    [1] pry(main)> class Foo
    [1] pry(main)*   module AvailableToClassAndInstance
    [1] pry(main)*     def bar
    [1] pry(main)*       "foo bar"
    [1] pry(main)*     end  
    [1] pry(main)*   end  
    [1] pry(main)*   include AvailableToClassAndInstance
    [1] pry(main)*   extend AvailableToClassAndInstance
    [1] pry(main)* end  
    => Foo
    [2] pry(main)> Foo.new.bar
    => "foo bar"
    [3] pry(main)> Foo.bar
    => "foo bar"
    

    A word of caution:

    Don't just randomly delegate everything that doesn't change state to class and instance because you'll start running into strange name clash issues. Do this sparingly and only after you checked nothing else is squashed.

提交回复
热议问题