Ruby:在结构中定义常量的语法 [英] Ruby: Syntax for defining a constant inside a Struct

查看:39
本文介绍了Ruby:在结构中定义常量的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下(正确的)Ruby 程序:

Consider the following (correct) Ruby program:

class Outer

  Inner = Struct.new(:dummy) do
    CONST = 'abce'
    def fun
      puts(dummy)
    end
  end

end

obj = Outer::Inner.new(15)
obj.fun
puts(Outer::CONST)

为什么我必须写Outer::CONST 而不是Outer::Inner::CONST?

Why do I have to write Outer::CONST instead of Outer::Inner::CONST?

我对传递给 Struct::new 的块的理解是 self 绑定到 Outer::Inner,事实上,我们可以看到方法(fun)附加在Inner类上;但 CONST 显然不是.

My understanding of the block passed to Struct::new was that self is bound to Outer::Inner, and indeed, we can see that the method (fun) is attached to the Inner class; but CONST obviously is not.

推荐答案

发生这种情况是因为常量是在当前命名空间中定义的.classmodule 关键字定义命名空间,但 Struct.new(就像 Class.new)没有.

This happens because the constant is defined in the current namespace. The class and module keywords define namespaces, but Struct.new (just like Class.new) does not.

为了在 Struct 的作用域下定义常量,你必须使用 self::

In order to define the constant under the Struct's scope, you have to use self::

class Outer
  Inner = Struct.new(:dummy) do
    self::CONST = 'abce'
  end
end

Outer::Inner::CONST
#=> 'abce'

Outer::CONST
#=> NameError uninitialized constant Outer::CONST

这篇关于Ruby:在结构中定义常量的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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