Confusion with constant look up

Xavier Noria wrote in post #1122939:

it is interpreted. Thus, in Rails const_missing is triggered only once
per
constant.

In Ruby why is the exception?

class C
  @x = 0
    def self.const_missing(*)
      1 # !> unused literal ignored
      @x=+1
    end
    def self.val
      p @x
    end
end

C::X # => 1
C::Y # => 1
C.val # => 1
# >> 1

I expected C.val should print `2`.

···

--
Posted via http://www.ruby-forum.com/\.

Xavier Noria wrote in post #1123075:

> The constants API and nesting are totally different concepts.
> and Module#constants here:
>
> Class: Module (Ruby 2.0.0)

Okay! I tried the code below :

module A
  module B
    Z = 2
  end
  X=10
end
module A::B
  module C
    Y =10
  end
end
A.constants
# => [:B, :X]
A::b::C::Y # => 10

It seems Module#constants - which Returns an array of the names of the
constants accessible in mod A. Not from the nested modules. Now my
questions is - Can we do something by which A.constants can output as
[:B, :X,:Z,:C,:Y] ?

There is no builtin way to do this, but you can easily program it:

    def recursive_constants(mod)
      constants =
      mod.constants.each do |constant|
        constants << constant
        value = mod.const_get(constant)
        constants += recursive_constants(value) if value.is_a?(Module)
      end
      constants
    end

    module A
      module B
        Z = 2
      end
      X=10
    end

    module A::B
      module C
        Y =10
      end
    end

    recursive_constants(A) # => [:B, :Z, :C, :Y, :X]

Xavier

···

On Tue, Oct 1, 2013 at 9:52 PM, Love U Ruby <lists@ruby-forum.com> wrote:

> On Tue, Oct 1, 2013 at 9:21 PM, Love U Ruby <lists@ruby-forum.com> > > wrote:

The code has a typo, should be

    @x += 1

rather than

    @x = +1

Xavier