From: "Jesús Gabriel y Galán" Date: 2010-07-31T17:59:51+09:00 Subject: Re: Beginner help needed: use a class def to create new instance On Sat, Jul 31, 2010 at 2:06 AM, Steve P. wrote: > Jesús Gabriel y Galán, > > I was able to accomplish (at least crudely) moving code from the main > body to the class. I felt this was worth doing because I want as much > logic as possible in the class. (Is this a worthy thing??) > > As you advised, I was able to create my new instance using a method that > returned an object. > > Could you please take a look at how I implemented these two methods? > Account.setupaccount, Account.report > > Is this how you would have structured it? > Any tips or comments greatly appreciated. > Steve. > > #!/usr/bin/ruby > class Account >  attr_reader :nbr, :name, :coa >  def initialize(nbr,name,coa) >    @nbr=nbr >    @name=name >    setcoa(coa) >  end >  def setcoa(coa) >    if ["income", "expense", "asset", "liability", >     "capital"].include?(coa) then >      @coa=coa >    else >      puts "Error, defaulted to expense" >      @coa="expense" >    end >  end Maybe call this coa=, as it's a setter? def coa=(coa) .... end >  def Account.setupaccount def Account.setup_account is more idiomatic. Also I usually do def self.setup_account, but that's a matter of taste, I guess. >  #data entry routine inside class, not in main code body. >    print "enter acct nbr: ";nbr=gets.chomp >    print "enter name: ";name=gets.chomp >    print "enter presen: ";coa=gets.chomp >    return Account.new(nbr,name,coa) >  end >  def Account.report(acct) >  #reporting code inside class, not in main body. >    puts "===Account Number Listing===" >    puts "Account Nbr:         #{acct.nbr}" >    puts "Account Name:        #{acct.name}" >    puts "Account CofA:        #{acct.coa}" >  end > end > ##Start of main code body ## > newacct=Account.setupaccount > Account.report(newacct) > ##End of Main code body ## As I said, I don't really like having the user interaction inside the domain class. For reporting, specially, I would create a to_s method that formats the account info, and then have the caller of that method be the one writing to stdout or to a file or whatever: def to_s s=< When I clear my confusion about this, I will do something like > class Ledger < Account >  ##code to make an array of the Account objects and add more > functionality > end If you want an array of Account objects, you shouldn't inherit from Account, but rather have an instance variable that holds an array of Accounts: class Ledger def initialize @accounts = [] end ... end Jesus.