我知道 self
是实例方法中的实例。那么,self
是类方法内部的类吗?例如,以下内容是否适用于 Rails?
class Post < ActiveRecord::Base
def self.cool_post
self.find_by_name("cool")
end
end
最佳答案
没错。类方法中的 self
是类本身。 (也在类定义内部,例如 def self.coolpost
中的 self
。)
您可以使用 irb 轻松测试这些花絮:
class Foo
def self.bar
puts self.inspect
end
end
Foo.bar # => Foo
关于ruby - 在 Ruby 中,在类方法内部,self 是类还是实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4349446/