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__
···
--
Posted via http://www.ruby-forum.com/.