Simple name of a class?

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.

···

--
Posted via http://www.ruby-forum.com/.

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

···

On Thu, Jan 13, 2011 at 1:48 AM, Kedar Mhaswade <kedar.mhaswade@gmail.com> wrote:

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?

*
* 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

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

···

--
Posted via http://www.ruby-forum.com/.

For the fun of it here's another regexp

irb(main):001:0> %w{foo foo::bar}.map {|s| s[/^(?:.*::)?([^:]+)$/, 1]}
=> ["foo", "bar"]

:slight_smile:

robert

···

On Thu, Jan 13, 2011 at 6:23 AM, Brian Candler <b.candler@pobox.com> 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

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