gpt4 book ai didi

Ruby Koans - 词法范围的延续与继承层次结构

转载 作者:数据小太阳 更新时间:2023-10-29 07:53:23 24 4
gpt4 key购买 nike

我有机会在 StackOverflow 中四处看看,发现了我试图从 Ruby Koans (Ruby Koans: explicit scoping on a class definition part 2) 中更好地理解的同一个问题。

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

# ------------------------------------------------------------------

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 heirarachy? Why is it
# different than the previous answer?

根据链接中的解释,其他人(包括我自己)的主要困惑似乎是因为类定义:

class MyAnimals::Oyster < Animal
# stuff goes in here
end

我最初的想法是 MyAnimals::Oyster 意味着 Oyster 类是在 MyAnimals 中定义的。换句话说,我认为上面的代码类似于下面的代码:

class MyAnimals
class Oyster < Animal
# stuff goes in here
end
end

为了验证我的想法,我在 IRB 中做了以下操作:

class MyAnimals
LEGS = 2

class Bird < Animal
def legs_in_bird
LEGS
end
end
end

class MyAnimals::Oyster # You should notice that I'm not inheriting from Animal anymore
def legs_in_oyster
LEGS
end
end

如果我的推理是正确的,那么我希望下面的代码返回 2

MyAnimals::Oyster.new.legs_in_oyster # => NameError: uninitialized constant MyAnimals::Oyster::LEGS

因为这不返回 2,有人可以向我解释为什么它不返回 2 吗?

编辑:我忘了添加 Animal 类;这是:

class Animal
LEGS = 4
def legs_in_animal
LEGS
end

class NestedAnimal
def legs_in_nested_animal
LEGS
end
end
end

最佳答案

回到 Ruby 搜索值的顺序。第 1 步是“封闭范围”。当你像这样定义一个嵌套类时

class Animal
class Bird
end
end

'Bird' 包含在 'Animal' 范围内。

当你这样做的时候

class Animal
end

class Animal::Bird
end

虽然您已将“Bird”定义为嵌套在“Animal”中,但在您定义“Bird”时,封闭范围是global 范围。返回 IRB 并定义 LEGS = 0(在全局范围内)并再次尝试您的 Oyster。

关于Ruby Koans - 词法范围的延续与继承层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15101544/

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