Hi all,
I define two classes, one with and the other without initialize method.
But I can call them with the same method new. I am not sure how to
explain them but I guess there are some kinds of default settings within
Ruby. Any comments?
Thanks,
Li
class X
puts “x”
end
class Y
def initialize
puts “y”
end
end
X.new
Y.new
ruby variables4.rb
x
y
Exit code: 0
Hi –
On Mon, 18 Dec 2006, Li Chen wrote:
end
X.new
Y.new
ruby variables4.rb
x
y
Try the program with this line:
X.new
removed or commented out. You’ll get the same output. The reason is
that the statement:
puts “x”
is executed when the class definition is executed. puts “y”, however,
is inside an instance method (initialize), so it isn’t executed until
there’s an instance (and in this case, since it’s an
automatically-called constructor, you don’t have to call it
explicitly).
David
Try the program with this line:
X.new
removed or commented out. You’ll get the same output. The reason is
that the statement:
puts “x”
is executed when the class definition is executed. puts “y”, however,
is inside an instance method (initialize), so it isn’t executed until
there’s an instance (and in this case, since it’s an
automatically-called constructor, you don’t have to call it
explicitly).
Thanks David. Now I get the point.
Li