Beginner help needed: use a class def to create new instance

S

Steve P.

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! :)

Best Regards
Steve.

#!/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 promptedinput
print "Char name: ";chname=gets.chomp
print "Char Nick: ";chnick=gets.chomp
print "Char Quote: ";chquote=gets.chomp
# Need help here!
# What code goes here to add Character class instance?
# class instance name should be newchar
end
end

puts newchar.inspect #referencing added instance.

__END__
 
J

Jesús Gabriel y Galán

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=3DCharacter.new(da da da) from th= e
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)
=A0 @chname=3Dchname
=A0 =A0 @chnick=3Dchnick
=A0 =A0 @chquote=3DString.new
end
=A0 def addquote(quote)
=A0 @chquote=3Dquote if quote.length > 10
=A0 end
=A0 def self.from_prompted_input
=A0 =A0 print "Char name: =A0 =A0";chname=3Dgets.chomp
=A0 =A0 print "Char Nick: =A0 =A0";chnick=3Dgets.chomp
=A0 =A0 print "Char Quote: =A0 =A0 =A0 =A0 =A0";chquote=3Dgets.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.
 
S

Steve P.

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
def Account.setupaccount
#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 ##

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
 
J

Jesús Gabriel y Galán

Jes=FAs Gabriel y Gal=E1n,

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
=A0attr_reader :nbr, :name, :coa
=A0def initialize(nbr,name,coa)
=A0 =A0@nbr=3Dnbr
=A0 =A0@name=3Dname
=A0 =A0setcoa(coa)
=A0end
=A0def setcoa(coa)
=A0 =A0if ["income", "expense", "asset", "liability",
=A0 =A0 "capital"].include?(coa) then
=A0 =A0 =A0@coa=3Dcoa
=A0 =A0else
=A0 =A0 =A0puts "Error, defaulted to expense"
=A0 =A0 =A0@coa=3D"expense"
=A0 =A0end
=A0end

Maybe call this coa=3D, as it's a setter?

def coa=3D(coa)
....
end
=A0def 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.
=A0#data entry routine inside class, not in main code body.
=A0 =A0print "enter acct nbr: ";nbr=3Dgets.chomp
=A0 =A0print "enter name: ";name=3Dgets.chomp
=A0 =A0print "enter presen: ";coa=3Dgets.chomp
=A0 =A0return Account.new(nbr,name,coa)
=A0end
=A0def Account.report(acct)
=A0#reporting code inside class, not in main body.
=A0 =A0puts "=3D=3D=3DAccount Number Listing=3D=3D=3D"
=A0 =A0puts "Account Nbr: =A0 =A0 =A0 =A0 #{acct.nbr}"
=A0 =A0puts "Account Name: =A0 =A0 =A0 =A0#{acct.name}"
=A0 =A0puts "Account CofA: =A0 =A0 =A0 =A0#{acct.coa}"
=A0end
end
##Start of main code body ##
newacct=3DAccount.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=3D<<EOF
=3D=3D=3DAccount Number Listing=3D=3D=3D
Account Nbr: #{acct.nbr}
Account Name: #{acct.name}
Account CofA: #{acct.coa}
EOF
s
end
When I clear my confusion about this, I will do something like
class Ledger < Account
=A0##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 =3D []
end
...
end

Jesus.
 
B

Brian Candler

Steve said:
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 promptedinput
print "Char name: ";chname=gets.chomp
print "Char Nick: ";chnick=gets.chomp
print "Char Quote: ";chquote=gets.chomp
# Need help here!
# What code goes here to add Character class instance?
# class instance name should be newchar
end
end

I think you want a class method, not an instance method, since you're
creating a new object which doesn't have any relation to any existing
object.

class Character
def initialize(chname,chnick,chquote="")
@chname=chname
@chnick=chnick
@chquote=chquote
end
def self.promptedinput
print "Char name: ";chname=gets.chomp
print "Char Nick: ";chnick=gets.chomp
print "Char Quote: ";chquote=gets.chomp
new(chnam,chnick,chquote)
end
end

newchar = Character.promptedinput
puts newchar.inspect

Note that I modified your initialize method to accept chquote as an
optional third argument. If you don't want to do that, then::

def self.promptedinput
print "Char name: ";chname=gets.chomp
print "Char Nick: ";chnick=gets.chomp
print "Char Quote: ";chquote=gets.chomp
result = new(chname,chnick)
result.chquote = chquote
result
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top