Ruby: Calling class method from instance

后端 未结 9 2052
谎友^
谎友^ 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 17:59

    You're doing it the right way. Class methods (similar to 'static' methods in C++ or Java) aren't part of the instance, so they have to be referenced directly.

    On that note, in your example you'd be better served making 'default_make' a regular method:

    #!/usr/bin/ruby
    
    class Truck
        def default_make
            # Class method.
            "mac"
        end
    
        def initialize
            # Instance method.
            puts default_make  # gets the default via the class's method.
        end
    end
    
    myTruck = Truck.new()
    

    Class methods are more useful for utility-type functions that use the class. For example:

    #!/usr/bin/ruby
    
    class Truck
        attr_accessor :make
    
        def default_make
            # Class method.
            "mac"
        end
    
        def self.buildTrucks(make, count)
            truckArray = []
    
            (1..count).each do
                truckArray << Truck.new(make)
            end
    
            return truckArray
        end
    
        def initialize(make = nil)
            if( make == nil )
                @make = default_make()
            else
                @make = make
            end
        end
    end
    
    myTrucks = Truck.buildTrucks("Yotota", 4)
    
    myTrucks.each do |truck|
        puts truck.make
    end
    

提交回复
热议问题