【发布时间】:2021-06-24 20:13:55
【问题描述】:
我有一个 Ruby C 扩展;我将ext/foo/foo.c 中定义的类FooC 称为我拥有的那个文件中
void Init_foo(void)
{
VALUE cFoo = rb_const_get(rb_cObject, rb_intern("FooC"));
:
rb_define_const(cFoo, "BAR", 7);
:
这包含在lib/foo.rb 中的扩展的“Ruby 部分”中
class FooC ; end
require 'foo/foo'
class Foo < FooC
class << self
def puts_bar
puts BAR
end
:
end
:
end
没想到,我得到一个错误
NameError: uninitialized constant #<Class:Foo>::BAR
我原以为 Ruby 不会在 Foo 命名空间中找到 BAR,但会搜索 FooC 找到它的位置。奇怪的是,如果我使用Foo::BAR 或self::BAR,错误就会消失,而Foo instance 方法中的类似用法根本不会给我任何错误。
有人知道为什么我需要在单例方法中对常量进行这种看似多余的限定吗?
[编辑]
根据下面有趣的答案,我确认在适当的类方法中不需要此限定:
class Foo < FooC
def self.puts_bar
# no NameError here
puts BAR
end
:
end
而不是特征类的实例方法。
【问题讨论】:
标签: ruby ruby-c-extension