In Ruby, inside a class method, is self the class or an instance?

ma11hew28 picture ma11hew28 · Dec 3, 2010 · Viewed 11.8k times · Source

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

Answer

St&#233;phan Kochen picture Stéphan Kochen · Dec 3, 2010

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