我知道self
是实例方法中的实例。那么,self
是类方法中的类吗?例如,下面的代码可以在Rails中运行吗?
class Post < ActiveRecord::Base
def self.cool_post
self.find_by_name("cool")
end
end
发布于 2010-12-04 04:13:58
这是正确的。类方法中的self
就是类本身。(也在类定义中,比如def self.coolpost
中的self
。)
你可以很容易地用irb测试这些花边新闻:
class Foo
def self.bar
puts self.inspect
end
end
Foo.bar # => Foo
https://stackoverflow.com/questions/4349446
复制相似问题