开发者

How to get a ruby class name and field name on rails

开发者 https://www.devze.com 2023-01-23 02:06 出处:网络
u=User.find(:first) u.to_s => \"#<User:0x9b017ac>\" 开发者_如何学JAVAhow can i output User this class stringThe most \"right\" way from Ruby documentation is to use u.class.name
 u=User.find(:first)
 u.to_s
 => "#<User:0x9b017ac>"
开发者_如何学JAVA

how can i output User this class string


The most "right" way from Ruby documentation is to use u.class.name Updated: the answer - u.name.to_s that was selected as correct - not right, cause:

for example:

class A
  def self.to_s
    "BBB"
  end
end

ruby-1.8.7-p302 > a.class.to_s
 => "BBB" 
ruby-1.8.7-p302 > a.class.name
 => "A" 


If you want to get the class name, try:

u.class.to_s

Edit:

As Sergey pointed out in his answer it is better to use

u.class.name

I believe that is because to_s could be overwritten and it could possibly return a different string that the one returned by name.


Try u.inspect and see if any of that info fits your needs.

0

精彩评论

暂无评论...
验证码 换一张
取 消