以下示例中如何打印ValidatorStatus
类名?
class ValidatorStatus
def initialize(host, msg)
@host = host
@msg = msg
end
attr_accessor :host
attr_accessor :msg
def to_s
puts %|How to have this print *ValidatorStatus*
by dynamically discovering class name?
also if im a subclass of this should print
the subclass name|
end
end
答案 0 :(得分:4)
self.class.name
只是你想要的。但是,当您添加限制时不使用self
:
public_send(:class).name
答案 1 :(得分:1)
def to_s
self.class.name
end
答案 2 :(得分:0)
正如其他人所说,正确的答案是self.class.name
如果您想获得创意,可以使用:
class A
def to_s
Module.nesting.first.to_s
end
end
puts A.new
# A
这里没有self
,甚至没有隐含的,隐藏的。{/ p>
它不会返回子类:
class B < A
end
puts B.new
# A
另一种可能性是解析当前文件:
class C < A
def to_s
File.readlines(__FILE__).take(__LINE__).reverse.join[/(?<=^class )\w+/]
end
end
puts C.new
# C