There is a class like this.

module Foo
  class Bar
  end
end

And I want to get the class name of Bar without Foo.

bar = Foo::Bar.new
bar.class.to_s.match('::(.+)$'){ $1 }

I could get the class name by this code, but I don't think this is a best way to get it.

Is there better way to get the name of class without namespace?

推荐答案

The canonical way to do this is to invoke Object#class and Module#name. For example:

bar.class.name.split('::').last
#=> "Bar"

Ruby相关问答推荐

当bsearch将数组中的第一个元素与2个值匹配时,它返回nil.为什么?

我可以在Ruby中以散列的形式访问方法的关键字参数吗?

如何在 Ruby 中反转数字的字节顺序

每次调用返回新的 REST 响应的 Ruby Rspec class_double

指南针手表:未定义的方法存在吗?对于文件:类

使用 Ruby,是否可以将 BigDecimal("1") / BigDecimal("3") 打印为 0.3333333333333... 到任意长度?

将数组转换 for each 元素的嵌套哈希

Ruby 中的内联注释

如何在 Ruby 中合并多个哈希?

判断Ruby中的目录是否为空

如何记录在 Ruby 程序中调用的每个方法?

Ruby:子字符串到一定长度,也到子字符串中的最后一个空格

由模块中定义的另一个覆盖方法

如何在 ruby​​ net/http 中实现 cookie 支持?

Ruby on rails - 静态方法

当我将参数传递给脚本时,使用 gets() 会出现没有这样的文件或目录错误

Ruby 中的=~运算符是什么?

何时在 Ruby 中使用 `require`、`load` 或 `autoload`?

如何重命名 gemset?

如何在 Mac OS Sierra 10.12 上安装 Nokogiri