I don't think there's anything for handling this in core/standard library.
As an alternative to custom written methods there is always activesupport:
require 'active_support/core_ext/string/inflections' Cowsay::Character::Stegosaurus.name.demodulize #=> "Stegosaurus" Cowsay::Character::Stegosaurus.name.deconstantize #=> "Cowsay::Character"
These methods are implemented as follows:
def demodulize(path) path = path.to_s if i = path.rindex('::') path[(i+2)..-1] else path end end def deconstantize(path) path.to_s[0, path.rindex('::') || 0] # implementation based on the one in facets' Module#spacename end
Take a look into docs if interested in more methods.
As to
A From A::B::C
If you'd require the whole activesupport, you'd get bunch of Module methods, including parent:
require 'active_support' Cowsay::Character::Stegosaurus.parent #=> Cowsay
If you're not going to use it extensively, I recommend to just grab the needed methods from activesupport and put it into some helper, because loading it whole might be an overkill.
A::B::Cto a string? Note that in this exampleAis a module, butBandCare not modules, not even Ruby objects, so the best you could do isAor"A", and"B"and"C". Since you are ending up with strings anyway, why avoid convertingA::B::Cto a string, as what you have is a very easy way to do it?A::B::Ctells us there are three nested modules,A,A::BandA::B::C.BandCare not modules. If you defined modulesA::CandB::C, what would it mean to refer to moduleC?split("::")[2]is not that bad. Certainly not as bad as requiring activesupport. It is simple and does the job.