The name method of class Class returns the full name of a class (e.g.
::). Is there a way to get just the simple
name?
e.g.
module CLI
class Yes
…
end
…
end
What method would return “Yes” (and not “CLI::Yes”) when I have an
instance of the Yes class (e.g. CLI::Yes.new.class.)?
Thanks in advance.
On Thu, Jan 13, 2011 at 1:48 AM, Kedar M.
[email protected] wrote:
The name method of class Class returns the full name of a class (e.g.
::). Is there a way to get just the simple
name?
I couldn’t see one defined here:
http://www.ruby-doc.org/core/classes/Module.html#M000474
mod.name → string
Returns the name of the module mod. Returns nil for anonymous modules.
http://www.ruby-doc.org/core/classes/Module.src/M000474.html
/*
Perhaps something like:
class Module
def path_last_name()
if (i = (r = name).rindex(‘:’)) then r[0…i] = ‘’ end
r
end
end
class Module
def relative_name
name.gsub(/^.*::/,’’)
end
end
class Foo; class Bar; end; end
puts Foo.new.class.relative_name
puts Foo::Bar.new.class.relative_name
On Thu, Jan 13, 2011 at 6:23 AM, Brian C. [email protected]
wrote:
class Module
def relative_name
name.gsub(/^.*::/,‘’)
end
end
class Foo; class Bar; end; end
puts Foo.new.class.relative_name
puts Foo::Bar.new.class.relative_name
For the fun of it here’s another regexp
irb(main):001:0> %w{foo foo::bar}.map {|s| s[/^(?:.*::)?([^:]+)$/, 1]}
=> [“foo”, “bar”]

robert