[RCR] Module#nesting (NOT the class method - instance method)

Discussion in 'Ruby' started by ara.t.howard@noaa.gov, Feb 5, 2007.

  1. Guest

    harp:~ > cat a.rb
    class Module
    def nesting
    parent, child = nil
    name.split('::').inject(Object){|parent, child| parent.const_get child}
    Object == parent ? nil : parent
    end
    end

    class A
    class B
    class C
    class D
    end
    end
    end
    end

    p A.nesting
    p A::B.nesting
    p A::B::C.nesting
    p A::B::C::D.nesting


    harp:~ > ruby a.rb
    nil
    A
    A::B
    A::B::C

    -a
    --
    we can deny everything, except that we have the possibility of being better.
    simply reflect on that.
    - the dalai lama
    , Feb 5, 2007
    #1
    1. Advertising

  2. Trans Guest

    Re: Module#nesting (NOT the class method - instance method)

    On Feb 5, 3:23 pm, wrote:
    > harp:~ > cat a.rb
    > class Module
    > def nesting
    > parent, child = nil
    > name.split('::').inject(Object){|parent, child| parent.const_get child}
    > Object == parent ? nil : parent
    > end
    > end
    >
    > class A
    > class B
    > class C
    > class D
    > end
    > end
    > end
    > end
    >
    > p A.nesting
    > p A::B.nesting
    > p A::B::C.nesting
    > p A::B::C::D.nesting
    >
    > harp:~ > ruby a.rb
    > nil
    > A
    > A::B
    > A::B::C


    irb(main):001:0> require 'facets/core/module/nesting'
    => true
    irb(main):002:0> class A
    irb(main):003:1> class B
    irb(main):004:2> class C
    irb(main):005:3> class D
    irb(main):006:4> end
    irb(main):007:3> end
    irb(main):008:2> end
    irb(main):009:1> end
    => nil
    irb(main):010:0> A.nesting
    => [A]
    irb(main):011:0> B.nesting
    NameError: uninitialized constant B
    from (irb):11
    from :0
    irb(main):012:0> A::B.nesting
    => [A, A::B]
    irb(main):013:0> A::B::C.nesting
    => [A, A::B, A::B::C]
    irb(main):014:0> A::B::C::D.nesting
    => [A, A::B, A::B::C, A::B::C::D]

    class Module
    def nesting
    n = []
    name.split(/::/).inject(self){ |mod, name| c =
    mod.const_get(name) ; n << c ; c }
    return n
    end
    end

    T.
    Trans, Feb 5, 2007
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. gga
    Replies:
    3
    Views:
    156
    William Morgan
    Feb 19, 2005
  2. Trans
    Replies:
    10
    Views:
    297
    Sean O'Halpin
    Sep 16, 2005
  3. Trans
    Replies:
    8
    Views:
    114
  4. Raj Singh
    Replies:
    2
    Views:
    196
    Rick DeNatale
    May 29, 2008
  5. Greg Hauptmann
    Replies:
    9
    Views:
    245
    Loren Segal
    Jun 16, 2008
Loading...

Share This Page