如何在Ruby中通过父类直接引用并调用子类定义的常量?

2026-04-11 15:350阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

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

如何在Ruby中通过父类直接引用并调用子类定义的常量?

在Ruby中,要从父类访问子类的常量,可以使用类名加上常量名的方式。以下是一个示例:

rubymodule Foo class Base TEST_CONSTANT='Hello'

def test puts Base::TEST_CONSTANT end endend

Foo::Base.new.test

在 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 这似乎有效 – 它强制不断查找范围到当前实例的类

如何在Ruby中通过父类直接引用并调用子类定义的常量?

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'

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

如何在Ruby中通过父类直接引用并调用子类定义的常量?

在Ruby中,要从父类访问子类的常量,可以使用类名加上常量名的方式。以下是一个示例:

rubymodule Foo class Base TEST_CONSTANT='Hello'

def test puts Base::TEST_CONSTANT end endend

Foo::Base.new.test

在 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 这似乎有效 – 它强制不断查找范围到当前实例的类

如何在Ruby中通过父类直接引用并调用子类定义的常量?

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'