From: Stefano Crocco Date: 2007-01-10T01:30:30+09:00 Subject: Re: with and without initialize method Alle 17:18, marted狸 9 gennaio 2007, Li Chen ha scritto: > Hi all, > > I try to understand some concepts in Ruby. I define two classes, one > with and the other without initialize method. In order to call the > methods defined in each class I need to call new/initialize method > first. Why is that? > > > Thanks, > > Li > > ##################### > class X > def hello_1 > puts 'Hello_1' > end > end > > a=X.new > a.hello_1 > > > #################### > class Y > def initialize > end > > def hello_2 > puts'Hello_2' > end > end > > b=Y.new > b.hello_2 > > ######screen output > > >ruby test3.rb > > Hello_1 > Hello_2 > > >Exit code: 0 The methods you defined are instance methods, i.e they must be called using instances of the class as receiver; you can't call them from the class themselves. You need to call new because new returns an instance of the class. In the first case, where you don't define initialize, the initialize method of the base class (Object) is called. If you want to call methods from the class (X.a_method), you must define them this way: class X def X.a_method #method implementation end end X.a_method I hope this helps Stefano