开发者

Ruby current class

开发者 https://www.devze.com 2023-01-26 14:52 出处:网络
How do I deter开发者_StackOverflow社区mine the current open class in Ruby?Inside the class itself:

How do I deter开发者_StackOverflow社区mine the current open class in Ruby?


Inside the class itself:

class_name = self.class

On an initialized object named obj:

class_name = obj.class


Inside of a class definition body, self refers to the class itself. Module#name will tell you the name of the class/module, but only if it actually has one. (In Ruby, there is no such thing as a "class name". Classes are simply objects just like any other which get assigned to variables just like any other. It's just that if you happen to assign a class object to a constant, then the name method will return the name of that constant.)

Example:

puts class Foo
  name
end
# Foo

But:

bar = Class.new
bar.name # => nil
BAR = bar
bar.name #=> 'BAR'


if you have obj = SomeClass.new you get the class with obj.class


If you're looking to compare via the class name (string):

class Foo
  def my_class_name_is
    self.class.name
  end
end

Foo.new.my_class_name_is
=> "Foo" 


In my case, the name method was overwrote, I find to_s give me this same result

class Foo
 puts self.name
 puts self.to_s
end
#=> Foo
#=> Foo
0

精彩评论

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