From: Gunther Diemant Date: 2011-03-07T20:50:44+09:00 Subject: Re: basic programming question, help please --0016364d2cbd9226b3049de316cb Content-Type: text/plain; charset=ISO-8859-1 You want a class method, not an instance method. class Square def count1 puts "I am instance method" end def self.count2 puts "I am class method" end end sqr = Square.new sqr.count1 #=> I am instance method sqr.count2 #=> NoMethodError Square.count1 #=> NoMethodError Square.count2 #=> I am class method On Mon, Mar 7, 2011 at 12:39 PM, Kaye Ng wrote: > class Square > def initialize > if defined?(@@number_of_squares) > @@number_of_squares = @@number_of_squares + 1 > else > @@number_of_squares = 1 > end > end > def self.count > @@number_of_squares > end > end > > a = Square.new #would return 1 > b = Square.new #would return 2 > puts Square.count #2 would be printed on the screen > > -------------------------------------------------------------------- > > My question is: why is the "self" necessary in "def self.count". > I don't understand the logic behind it. > > (I know that I can also type "def Square.count" instead of "def > self.count") > > Thanks guys! > > -- > Posted via http://www.ruby-forum.com/. > > --0016364d2cbd9226b3049de316cb--