5

Is there a better way to get class/module name viz, C from A::B::C, B from A::B::C, and A From A::B::C. The following code uses string and split to get "Stegosaurus" from Cowsay::Character::Stegosaurus, How to do away with string and split?

require 'cowsay' x = Cowsay.random_character().class x.name.split("::")[2] require 'cowsay' true x = Cowsay.random_character().class Cowsay::Character::Stegosaurus x.name.split("::")[2] "Stegosaurus" 
3
  • Am I correct in my understanding that you wish to extract each element without converting A::B::C to a string? Note that in this example A is a module, but B and C are not modules, not even Ruby objects, so the best you could do is A or "A", and "B" and "C". Since you are ending up with strings anyway, why avoid converting A::B::C to a string, as what you have is a very easy way to do it? Commented Oct 23, 2016 at 21:36
  • If I was not clear in my comment above, A::B::C tells us there are three nested modules, A, A::B and A::B::C. B and C are not modules. If you defined modules A::C and B::C, what would it mean to refer to module C? Commented Oct 23, 2016 at 22:01
  • 3
    IMO split("::")[2] is not that bad. Certainly not as bad as requiring activesupport. It is simple and does the job. Commented Oct 23, 2016 at 22:27

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good point about extracting the useful methods if you need them. That's what's great about having open-source: You can always borrow parts if you need them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.