Last Updated: February 25, 2016
·
581
· mejarc

The value of a constant: inherited vs. lexical scope

An example from Ruby Koans:

class Animal
  LEGS = 4

  class MyAnimals
    LEGS = 2

    class Bird < Animal
      def legs_in_bird
        LEGS
      end
    end
  end
end

How many legs does a Bird have? Two.

Consider this:

class MyAnimals::Oyster < Animal
  def legs_in_oyster
    LEGS
  end
end

How many legs does an Oyster have (at least, in this weird scenario)? Four.