gpt4 book ai didi

Ruby 范围,常量优先级 : lexical scope or inheritance tree

转载 作者:数据小太阳 更新时间:2023-10-29 06:51:51 25 4
gpt4 key购买 nike

我将向您展示来自 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**?

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

最佳答案

这里有答案: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]

看出区别了吗?

关于Ruby 范围,常量优先级 : lexical scope or inheritance tree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13661193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com