# With and without initialize method

**URL:** <https://www.ruby-forum.com/t/with-and-without-initialize-method/79660>\
**Category:** Ruby\
**Created:** [December 17, 2006, 8:15pm UTC](https://www.ruby-forum.com/t/with-and-without-initialize-method/79660 "2006-12-17T20:15:42Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [December 17, 2006, 8:15pm UTC](https://www.ruby-forum.com/t/with-and-without-initialize-method/79660/1 "2006-12-17T20:15:42Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [December 17, 2006, 8:31pm UTC](https://www.ruby-forum.com/t/with-and-without-initialize-method/79660/2 "2006-12-17T20:31:02Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [December 17, 2006, 8:59pm UTC](https://www.ruby-forum.com/t/with-and-without-initialize-method/79660/3 "2006-12-17T20:59:04Z")

</div>

> 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
