在ruby from类中,函数没有self,如何获取当前类名?
在下面的示例中,如何打印在ruby from类中,函数没有self,如何获取当前类名?,ruby,Ruby,在下面的示例中,如何打印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 dynamicall
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
这正是你想要的。但当您添加不使用self
的限制时:
public_send(:class).name
正如其他人所说,正确答案是
self.class.name
如果你想获得创造性,你可以使用:
class A
def to_s
Module.nesting.first.to_s
end
end
puts A.new
# A
这里没有自我,甚至没有一个隐含的、隐藏的自我
但它不返回子类:
class B < A
end
puts B.new
# A
B类
另一种可能是解析当前文件:
class C < A
def to_s
File.readlines(__FILE__).take(__LINE__).reverse.join[/(?<=^class )\w+/]
end
end
puts C.new
# C
C类File.readlines(uuu File_uuu)。take(uu LINE_uu)。reverse.join[/(?声称“没有自我”是荒谬的……当然它也隐含地使用了self
,因为它只是self.public\u send(:class).name
)的语法糖。我最喜欢最后一个。暴力FTW。
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