Search code examples
rubyclassinstanceselfclass-method

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


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

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