Alex Rivera | Logout

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

Asked 2010-12-03T20:08:56.730
18

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
Edit
Report

1 Answer

5
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
answered 2010-12-03T20:15:49.400

Your Answer