I have different objects, for example Article
and Medium
. When I use a helper, I would like to determine the name of the object (for example Article
or Medium
). How can I do that?
我有不同的对象,例如文章和媒介。当我使用助手时,我想确定对象的名称(例如Articleor Medium)。我怎么做呢?
2 个解决方案
#1
10
See http://ruby-doc.org/core-1.9.3/Object.html#method-i-class
看到http://ruby-doc.org/core-1.9.3/Object.html method-i-class
a = Article.new
a.class
# => Article
a.class.to_s
# => "Article"
also take a look at is_a? and respond_to?. It's generally better to use duck typing with respond_to?
than the name of a class (generally).
看一下is_a?respond_to ?。在respond_to中使用duck typing通常会更好一些。而不是类的名称(通常)。
#2
-2
It is impossible. Constants and variables refer to the object. There is no way to get the name of it.
这是不可能的。常量和变量指的是对象。没有办法知道它的名字。
Article = Object.new
See that the value Article
does not include information about its name:
请注意,value文章不包含关于其名称的信息:
Article
# => <#Object...>
#1
10
See http://ruby-doc.org/core-1.9.3/Object.html#method-i-class
看到http://ruby-doc.org/core-1.9.3/Object.html method-i-class
a = Article.new
a.class
# => Article
a.class.to_s
# => "Article"
also take a look at is_a? and respond_to?. It's generally better to use duck typing with respond_to?
than the name of a class (generally).
看一下is_a?respond_to ?。在respond_to中使用duck typing通常会更好一些。而不是类的名称(通常)。
#2
-2
It is impossible. Constants and variables refer to the object. There is no way to get the name of it.
这是不可能的。常量和变量指的是对象。没有办法知道它的名字。
Article = Object.new
See that the value Article
does not include information about its name:
请注意,value文章不包含关于其名称的信息:
Article
# => <#Object...>