Skip to content

Instantly share code, notes, and snippets.

@kinopyo
Created April 20, 2012 07:23
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kinopyo/2426829 to your computer and use it in GitHub Desktop.
Save kinopyo/2426829 to your computer and use it in GitHub Desktop.
Ruby: Get module name or class name without module
n = Notification::Answer.new
n.class.name.split('::').last || ''
# => "Answer"
n.class.name.split('::').first || ''
# => "Notification"
@phstc
Copy link

phstc commented Jul 23, 2013

Another way...

n = Notification::Answer.new
n.class.to_s.gsub(/^.*::/, '')
# => "Answer"
n.class.to_s.gsub(/::.*/, '')
#=> "Notification"

@rob-murray
Copy link

Or with ActiveSupport in Rails;

n = Notification::Answer.new
# => "Answer"
n.class.name.demodulize

@MrPlazmaDude
Copy link

class_name

Copy link

ghost commented Feb 28, 2018

An update on the comment from @phstc that works for nested modules:

n = Foo::Bar::Bazz.new

n.class.to_s.gsub(/^.*::/, '')
# => "Bazz"
n.to_s.gsub(/(.*)::.*/, '\1')
# => "Foo::Bar"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment