Ruby代码片段:得到当前类名
在bigbold上看到Get the currently running method name in Ruby
代码片段:
module Kernel
private
def this_method_name
caller[0] =~ /`([^']*)'/ and $1
end
end
class Foo
def test_method
this_method_name
end
end
puts Foo.new.test_method # => test_method
对其caller[0] =~ /`([^']*)'/ and $1这种语法结构甚是不解,后来又发现这么写也行caller[0][/`([^']*)'/, 1],于是查了下参考手册中private
def this_method_name
caller[0] =~ /`([^']*)'/ and $1
end
end
class Foo
def test_method
this_method_name
end
end
puts Foo.new.test_method # => test_method
caller的用法,还算明白一点;
caller
返回[文件名、行号、方法名]