2010-12-03 21 views
17

我知道self是实例方法中的实例。那么,self是类方法中的类吗?例如,下面的工作将在Rails中进行吗?在Ruby中,类方法内部是自己的类还是实例?

class Post < ActiveRecord::Base 
    def self.cool_post 
    self.find_by_name("cool") 
    end 
end 
+5

,除非指定要添加到下面的答案,因为红宝石将始终评估接收机的自我,你上面的代码可以直接调用`find_by_name `没有自我:) – brad 2010-12-03 20:18:22

回答

21

这是正确的。 self里面的类方法就是类本身。

class Foo 
    def self.bar 
    puts self.inspect 
    end 
end 

Foo.bar # => Foo 
5
class Test 
    def self.who_is_self 
     p self 
    end 
end 

Test.who_is_self 

输出:

测试(同时,也是类定义内,如def self.coolpostself

您可以轻松地与IRB测试这些花絮

现在,如果你想有一个Rails的具体的解决方案,这就是所谓的named_scopes:

class Post < ActiveRecord::Base 
    named_scope :cool, :conditions => { :name => 'cool' } 
end 

像这样来使用:

Post.cool 
4

简短的回答:

我喜欢做这些问题只是引发了irb或./script/console会话

和ñ你可以做以下看看神奇:

ruby-1.8.7-p174 > class TestTest 
ruby-1.8.7-p174 ?> def self.who_am_i 
ruby-1.8.7-p174 ?> return self 
ruby-1.8.7-p174 ?> end 
ruby-1.8.7-p174 ?> end 
=> nil 
ruby-1.8.7-p174 > TestTest.who_am_i 
=> TestTest 

快乐钓鱼!

5

很多答案了,但这里是为什么自我是类:

的点改变self到什么是点之前。所以,当你做foo.bar那么对于bar-方法,selffoo。类方法没有区别。当致电Post.cool_post时,您会将self更改为Post

这里需要注意的重要一点是,它不是如何定义方法来确定self,而是如何调用它。这就是为什么这个工程:

class Foo 
    def self.bar 
    self 
    end 
end 

class Baz < Foo 
end 

Baz.bar # => Baz 

或者这样:

module Foo 
    def bar 
    self 
    end 
end 

class Baz 
    extend Foo 
end 

Baz.bar # => Baz 
相关问题