我想从类名中获取资源名称,如:
“SequelAdapter :: UserGraph”
所以在这种情况下我想要用户。
目前我有这个代码可行,但非常难看:
klass = object.class.to_s
if start = klass =~ /[::][A-Za-z]*Graph/
finish = klass =~ /Graph/
klass = klass[start + 1, finish - start - 1]
end
有人能建议更好的方法吗?
答案 0 :(得分:1)
试试这个:
klass = object.class.to_s.match(/(\w+)Graph$/).captures[0]
klass
=> "User"
答案 1 :(得分:1)
普通ruby解决方案:
object = SequelAdapter::UserGraph.new
/(?<klass>[A-Za-z]*)Graph/.match( object.class.to_s )[1]
klass # => "User
对于ruby-2.0,请尝试以下操作:
/(?<klass>[A-Za-z]*)Graph/ =~ object.class.to_s
klass # => "User
如果您希望更准确regexp:
object = SequelAdapter::UserGraph.new
/(?<klass>[A-Z](?:[[[:alpha:]]])*)*Graph/ =~ object.class.to_s
klass # => "User