如何通过Ruby父类调用子类定义的常量?

更新于
2026-10-09 18:42:11
1阅读来源:SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计159个文字,预计阅读时间需要1分钟。

如何通过Ruby父类调用子类定义的常量?

在Ruby中,可以从父类访问子类的常量。以下是如何实现这一点的代码示例:

rubymodule Foo BASE_CONST='常量值'end

class Base include Foo

def test puts BASE_CONST endend

如何通过Ruby父类调用子类定义的常量?

在 Ruby中,如何从父类访问调用类的常量?

Module Foo class Base def test() #how do I access calling class's constants here? #ex: CallingClass.SOME_CONST end end end class Bar < Foo::Base SOME_CONST = 'test' end 这似乎有效 – 它强制不断查找范围到当前实例的类

module Foo class Base def test self.class::SOME_CONST end end end class Bar < Foo::Base SOME_CONST = 'test' end Bar.new.test # => 'test'

本文共计159个文字,预计阅读时间需要1分钟。

如何通过Ruby父类调用子类定义的常量?

在Ruby中,可以从父类访问子类的常量。以下是如何实现这一点的代码示例:

rubymodule Foo BASE_CONST='常量值'end

class Base include Foo

def test puts BASE_CONST endend

如何通过Ruby父类调用子类定义的常量?

在 Ruby中,如何从父类访问调用类的常量?

Module Foo class Base def test() #how do I access calling class's constants here? #ex: CallingClass.SOME_CONST end end end class Bar < Foo::Base SOME_CONST = 'test' end 这似乎有效 – 它强制不断查找范围到当前实例的类

module Foo class Base def test self.class::SOME_CONST end end end class Bar < Foo::Base SOME_CONST = 'test' end Bar.new.test # => 'test'