【问题标题】:confusion about ruby CONSTANT关于 ruby​​ CONSTANT 的困惑
【发布时间】:2014-02-19 14:18:08
【问题描述】:

假设一个关于 CONSTANT 变量的简单 ruby​​ 程序:

OUTER_CONST = 99
class Const
  def get_const
    CONST
  end
  CONST = OUTER_CONST + 1
end

puts Const.new.get_const

我假设Const.new.get_const 的结果应该是nil,但结果是100!我想知道为什么?

【问题讨论】:

  • 为什么要投票给我!请脱颖而出。

标签: ruby constants


【解决方案1】:

get_const 是一个方法,您在 CONST 定义之后调用它;所以当你调用它时,CONST 已经定义好了。

def get_const ... end 定义了一个方法,不执行其内容;当你在Const.new.get_const 行调用它时执行它的内容,所以当CONST 已经定义时。

另外:如果CONSTget_const调用时没有定义,你不会得到nil,而是NameError

class Const
  def get_const
    CONST
  end
end

Const.new.get_const #=> NameError: uninitialized constant Const::CONST

【讨论】:

  • 我猜想当 Class Const 被初始化时,CONST = OUTER_CONST + 1 还没有被执行。所以,我想知道ruby如何识别CONST的定义?这是我的问题。
  • @user2886717 当然,但请注意def get_const ... end 定义了一个方法,不执行其内容;你在调用它时执行它的内容(在Const.new.get_const 行),所以当CONST 已经定义时
  • @mdesantis 确定 :-)
【解决方案2】:

这是因为 Ruby 是 dynamic 并且持续查找发生在运行时。另请记住,您的脚本是按顺序评估的(即逐行)。

为了清楚起见,我添加了一些 cmets:

OUTER_CONST = 99

class Const
  def get_const
    CONST
  end

  CONST = OUTER_CONST + 1
  # the CONST constant is now
  # defined and has the value 100
end

# at this point the Const class
# and CONST constant are defined and can be used

# here you are calling the `get_const` method
# which asks for the value of `CONST` so the 
# constant lookup procedure will now start and
# will correctly pick up the current value of `CONST`
Const.new.get_const # => 100

【讨论】:

    猜你喜欢
    • 2014-03-21
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 2020-03-06
    • 2016-03-16
    • 2013-07-27
    • 1970-01-01
    相关资源
    最近更新 更多