simple name of a class?

K

Kedar Mhaswade

The name method of class Class returns the full name of a class (e.g.
<module-name>::<class-name>). 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.<what-method>)?

Thanks in advance.
 
C

Colin Bartlett

The name method of class Class returns the full name of a class (e.g.
<module-name>::<class-name>). 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
/*
* call-seq:
* mod.name -> string
*
* Returns the name of the module <i>mod</i>. Returns nil for
anonymous modules.
*/
VALUE
rb_mod_name(VALUE mod)
{
VALUE path = classname(mod);

if (!NIL_P(path)) return rb_str_dup(path);
return path;
}

Perhaps something like:

class Module
def path_last_name()
if (i = (r = name).rindex(':')) then r[0..i] = '' end
r
end
end
 
B

Brian Candler

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
 
R

Robert Klemme

class Module
=A0def relative_name
=A0 =A0name.gsub(/^.*::/,'')
=A0end
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]}
=3D> ["foo", "bar"]

:)

robert


--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top