With and without initialize method

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

--
Posted via http://www.ruby-forum.com/\.

Hi --

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

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

···

On Mon, 18 Dec 2006, Li Chen wrote:

--
Q. What's a good holiday present for the serious Rails developer?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black\)
    aka The Ruby book for Rails developers!
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)

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

···

--
Posted via http://www.ruby-forum.com/\.