Ruby:从实例调用类方法 [英] Ruby: Calling class method from instance

查看:53
本文介绍了Ruby:从实例调用类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,如何从类的实例之一调用类方法?说我有

class 卡车def self.default_make# 类方法.苹果电脑"结尾定义初始化# 实例方法.Truck.default_make # 通过类的方法获取默认值.# 但是:我希望避免提及卡车.似乎我在重复自己.结尾结尾

Truck.default_make 检索默认值.但是有没有一种方法可以不提及Truck 来表达这一点?好像应该有.

解决方案

与其引用类的字面名称,不如在实例方法中调用 self.class.whatever.

class Foodef self.some_class_method把自己结尾def some_instance_methodself.class.some_class_method结尾结尾打印类方法:"Foo.some_class_method打印实例方法:"Foo.new.some_instance_method

输出:

<前>类方法:Foo实例方法:Foo

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

  def initialize
    # Instance method.
    Truck.default_make  # gets the default via the class's method.
    # But: I wish to avoid mentioning Truck. Seems I'm repeating myself.
  end
end

the line Truck.default_make retrieves the default. But is there a way of saying this without mentioning Truck? It seems like there should be.

解决方案

Rather than referring to the literal name of the class, inside an instance method you can just call self.class.whatever.

class Foo
    def self.some_class_method
        puts self
    end

    def some_instance_method
        self.class.some_class_method
    end
end

print "Class method: "
Foo.some_class_method

print "Instance method: "
Foo.new.some_instance_method

Outputs:

Class method: Foo
Instance method: Foo

这篇关于Ruby:从实例调用类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆