【问题标题】:Ruby scopes, constants precedence: lexical scope or inheritance treeRuby 作用域、常量优先级:词法作用域或继承树
【发布时间】:2012-11-19 14:48:12
【问题描述】:

我将向您展示来自rubykoans 教程的代码 sn-p。考虑下一个代码:

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**?

实际上问题在于 cmets(我用星号突出显示了它(尽管它打算用粗体显示))。有人可以解释一下吗?提前致谢!

【问题讨论】:

    标签: ruby nested-class scopes


    【解决方案1】:

    这里有答案:Ruby: explicit scoping on a class definition。但也许不是很清楚。如果您阅读链接的文章,它将帮助您找到答案。

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

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

    class MyAnimals
      LEGS = 2
    
      class Bird < Animal
    
        p Module.nesting
        def legs_in_bird
          LEGS
        end
      end
    end
    

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

    还有

    class MyAnimals::Oyster < Animal
      p Module.nesting
    
      def legs_in_oyster
        LEGS
      end
    end
    

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

    看到区别了吗?

    【讨论】:

    • 包括 Module.nesting 使此答案成为您链接的答案的绝佳补充。
    猜你喜欢
    • 1970-01-01
    • 2017-07-10
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    相关资源
    最近更新 更多