Kaye Ng wrote in post #985934:
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.
It isn't necessary:
class Square
def initialize
if defined?(@@number_of_squares)
@@number_of_squares = @@number_of_squares + 1
else
@@number_of_squares = 1
end
end
def count
@@number_of_squares
end
end
a = Square.new
b = Square.new
puts a.count #2
...but the way in which you define the method determines how you can
call the method. You can choose to define a "class method" or an
"instance method". A class method is called using the class, and an
instance method is called using an object/instance of the class. You
have to decide how you want to call the method: with the class or an
instance.
In your case, I would suggest that Square.count makes more sense in
English where if you ask for a.count, it is not really clear what that
means.
(I know that I can also type "def Square.count" instead of "def
self.count")
You can also use a third syntax:
class Square
def Square.class_meth1
puts 'class_meth1'
end
def self.class_meth2
puts 'class_meth2'
end
class << self
def class_meth3
puts 'class_meth3'
end
end
end
--output:--
class_meth1
class_meth2
class_meth3
···
--
Posted via http://www.ruby-forum.com/\.