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

A

ara.t.howard

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
 
T

Trans

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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top