Question

I know that self is the instance inside of an instance method. So, then, is self the class inside of a class method? E.g., Will the following work in Rails?

class Post < ActiveRecord::Base
  def self.cool_post
    self.find_by_name("cool")
  end
end
Was it helpful?

Solution

That is correct. self inside a class method is the class itself. (And also inside the class definition, such as the self in def self.coolpost.)

You can easily test these tidbits with irb:

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

Foo.bar  # => Foo

OTHER TIPS

class Test
    def self.who_is_self
        p self
    end
end

Test.who_is_self

output:

Test

Now if you want a Rails specific solution, it's called named_scopes:

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

Used like this:

Post.cool

A lot of answers already, but here is why self is the class:

The dot changes self to whatever is before the dot. So, when you do foo.bar then for the bar-method, self is foo. There is no difference with class methods. When calling Post.cool_post, you'll change self to Post.

The important thing to note here is that it's not how the method is defined that determines self, but how it's called. This is why this works:

class Foo
  def self.bar
    self
  end
end

class Baz < Foo
end

Baz.bar # => Baz

Or this:

module Foo
  def bar
    self
  end
end

class Baz
  extend Foo
end

Baz.bar # => Baz

Short answer: yes

What I like to do with these questions is just fire up an irb or ./script/console session

and then you can do the following to see the magic:

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

Happy fishing!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top