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

Answers


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

Need Your Help

Laggy custom cursor is Flash

actionscript-3 flash cursor

Making a custom cursor in flash as3, I have replaced the cursor with a broomstick (simple vector movieclip). The code is the standard custom cursor code below:

How to write tweet IDs to a CSV file as strings

python python-2.7 pandas

I have a column which contains a list of tweet IDs. A tweet ID could get as long as this '475685437424427008'. When I write this to a CSV file using the data.to_csv() method they get written as flo...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.