Ruby Koans: explicit scoping on a class definition part 2

后端 未结 1 371
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-25 13:35

I wanted to clarify some things off of this original post. The answer suggested that Ruby searches for the constant definition in this order:

  1. The enclosing sco
相关标签:
1条回答
  • 2020-12-25 14:10

    I was just pondering the very same question from the very same koan. I am no expert at scoping, but the following simple explanation made a lot of sense to me, and maybe it will help you as well.

    When you define MyAnimals::Oyster you are still in the global scope, so ruby has no knowledge of the LEGS value set to 2 in MyAnimals because you never actually are in the scope of MyAnimals (a little counterintuitive).

    However, things would be different if you were to define Oyster this way:

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

    The difference is that in the code above, by the time you define Oyster, you have dropped into the scope of MyAnimals, so ruby knows that LEGS refers to MyAnimals::LEGS (2) and not Animal::LEGS (4).

    FYI, I got this insight from the following URL (referenced in the question you linked to):

    • https://groups.google.com/forum/#!topic/comp.lang.ruby/t5rtDNol3P8
    0 讨论(0)
提交回复
热议问题