From: Gary Wright Date: 2011-02-27T10:42:48+09:00 Subject: Re: Newbie question On Feb 26, 2011, at 8:29 PM, Marc Chanliau wrote: > In Ruby it seems you can instantiate a class inside the class itself or > outside. What is the accepted convention? > In the following example, instantiation is inside the class: > > class Person > attr_accessor :name, :age, :gender > > def initialize(name, age, gender) > @name = name > @age = age.to_i > @gender = gender > end > > # method to print a new person > def printIt > print " " > print name > print ", " > print age > print ", " > print gender > puts > end > > # generating instances and printing them from inside the class itself > person_instance = Person.new("Jessica", 17, "female") > person_instance.printIt > person_instance = Person.new("Marc", 60, "male") > person_instance.printIt > person_instance = Person.new("Linda", 56, "female") > person_instance.printIt > > end Your example is quite unusual. The scope of the 'person_instance' variable is only going to be within your class definition of Person. Basically you are creating several instances but then discarding any reference to them. After the 'end' that terminates the Person definition 'person_instance' won't be defined and so the instance won't be accessible. It is important to realize that Ruby class definitions are actually executable code. The code within the class..end block is executed in the order it is written so that by the time you get to your "Person.new" calls, the class is defined as well as 'initialize' and 'printit' so there isn't anything magical going on when you call Person.new. Note, that if you moved your Person.new calls to between the definition of initialize and printIt, they would fail because they would be executed before printIt was defined. Gary Wright