Ruby作用域,常量优先级:词法作用域或继承树

Pau*_*hiy 9 ruby nested-class scopes

我将从rubykoans教程中显示您的代码片段.考虑下一个代码:

class MyAnimals
LEGS = 2

  class Bird < Animal
    def legs_in_bird
      LEGS
    end
  end
end

def test_who_wins_with_both_nested_and_inherited_constants
  assert_equal 2, MyAnimals::Bird.new.legs_in_bird
end

# QUESTION: Which has precedence: The constant in the lexical scope,
# or the constant from the inheritance hierarchy?
# ------------------------------------------------------------------

class MyAnimals::Oyster < Animal
  def legs_in_oyster
    LEGS
  end
end

def test_who_wins_with_explicit_scoping_on_class_definition
  assert_equal 4, MyAnimals::Oyster.new.legs_in_oyster
end

# QUESTION: Now which has precedence: The constant in the lexical
# scope, or the constant from the inheritance hierarchy?  Why is it
# **different than the previous answer**?
Run Code Online (Sandbox Code Playgroud)

实际上问题是在评论中(我用星号突出显示它(虽然它打算用粗体表示)).有人可以解释一下吗?提前致谢!

Tod*_*odd 22

这在这里得到解答:Ruby:对类定义的显式范围.但也许它不是很清楚.如果您阅读链接的文章,它将帮助您解决问题.

基本上,Bird在声明范围内声明,MyAnimals在解析常量时具有更高的优先级.OysterMyAnimals命名空间中,但未在该范围内声明.

插入p Module.nesting每个类,向您展示封闭范围是什么.

class MyAnimals
  LEGS = 2

  class Bird < Animal

    p Module.nesting
    def legs_in_bird
      LEGS
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

产量: [AboutConstants::MyAnimals::Bird, AboutConstants::MyAnimals, AboutConstants]

class MyAnimals::Oyster < Animal
  p Module.nesting

  def legs_in_oyster
    LEGS
  end
end
Run Code Online (Sandbox Code Playgroud)

产量: [AboutConstants::MyAnimals::Oyster, AboutConstants]

看到不同?

  • 包含 `Module.nesting` 使这个答案成为您链接的答案的绝佳补充。 (2认同)