2011-03-28 66 views
19

我想澄清这个原始的post的一些东西。的回答表明红宝石的顺序搜索所述常数定义:Ruby Koans:在类定义第2部分的显式范围

  1. 封闭范围
  2. 任何外部范围(重复,直到顶层到达)
  3. 包括模块
  4. 超类(ES)
  5. 对象
  6. 内核

所以要澄清,在步骤(1-6)是否为legs_in_oyster找到的常量LEGS的值?它是否来自超类AnimalMyAnimals的范围是否被忽略,因为它不被视为封闭范围?这是由于明确的MyAnimals::Oyster类定义?

谢谢!只是想明白。这里是代码:

class Animal 
    LEGS = 4 
    def legs_in_animal 
    LEGS 
    end 

    class NestedAnimal 
    def legs_in_nested_animal 
     LEGS 
    end 
    end 
end 

def test_nested_classes_inherit_constants_from_enclosing_classes 
    assert_equal 4, Animal::NestedAnimal.new.legs_in_nested_animal 
end 

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

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? 
end 
+0

有人来问这个公案前:http://stackoverflow.com/questions/4627735/ruby​​ -express -scope-on-a-class-definition – 2011-03-28 22:21:16

+0

@Andrew - 我在帖子中指定。我只是想就这个话题进行更多的讨论,因为有些部分我不明白。我应该在那里发表评论吗? – 2011-03-29 01:29:48

+0

对不起,我没有注意到。 – 2011-03-29 01:32:44

回答

31

我只是在思考同一个问题,从同一个公司。我不是专家的范围,但下面的简单解释对我来说很有意义,也许它也会对你有所帮助。

当你定义MyAnimals::Oyster你仍然在全球范围内,使红宝石没有设置为2 MyAnimals因为你从来没有真正在的MyAnimals范围的LEGS值的知识(有点违反直觉)。

class MyAnimals 
    class Oyster < Animal 
    def legs_in_oyster 
     LEGS # => 2 
    end 
    end 
end 

不同的是,在上面的代码,由您定义Oyster的时候,你已经投进MyAnimals范围:

但是,如果你定义Oyster这样的事情会有所不同,所以红宝石知道LEGS是指MyAnimals::LEGS(2)而不是Animal::LEGS(4)。

仅供参考,我得到这个见解从以下URL(在这个问题引用链接到您):

+0

谢谢@bowsersenior!我看到了这一联系,但没有读得太多。用户错误。 – 2011-03-30 13:17:25

+0

我认为它应该是'Oyster 2012-12-20 12:25:28

+0

谢谢@AndreyBotalov!更新了代码以纠正它。 – bowsersenior 2012-12-21 00:30:09