From: "Jesús Gabriel y Galán" Date: 2010-07-27T15:43:41+09:00 Subject: Re: Beginner help needed: use a class def to create new instance On Tue, Jul 27, 2010 at 6:36 AM, Steve P. wrote: > I am attempting to put as much code inside classes as possible, to > economize the code in the main body. However, how do I create a new > class instance using only a method defined in a class? > > For instance, in the following code, I want to create a new Class > Character instance named newchar by fleshing out the code in the #'d > area. Is it possible? > > Otherwise, what is best practice? > > PS: I realize I can instantiate newchar=Character.new(da da da) from the > body of the code but that would require the prompting code be there > also. that would defeat my purpose. I hope I have given this enough > thought before posting! :-) Two considerations: - I tend to separate the domain objects from the code that interacts with the outside world to gather the data to populate that domain object (user typing, DB, etc). This way you gain flexibility, being able to add ways of loading or creating the object without modifying that class - If, in any case, you want the interaction with the user in that class, I would use a class method that returns an instance. If you have other ways of creating that instance you can add new methods for each case. For example: #!/usr/bin/ruby -w class Character attr_reader :chname, :chnick, :chquote def initialize(chname,chnick)   @chname=chname     @chnick=chnick     @chquote=String.new end   def addquote(quote)   @chquote=quote if quote.length > 10   end   def self.from_prompted_input     print "Char name:    ";chname=gets.chomp     print "Char Nick:    ";chnick=gets.chomp     print "Char Quote:          ";chquote=gets.chomp Character.new chname, chnick,chquote end end puts Character.from_prompted_input.inspect What you had in mind couldn't work, because your method was an instance method, so from the outside you still needed someone to call Character.new(x,y,z).promptedinput. Having class methods to instantiate objects of the class in different ways is a pretty typical idiom, check for example the Date class in core: http://ruby-doc.org/core/classes/Date.html The methods civil, commercial, etc are class methods that return an instance, constructed in a different way. Jesus.