If I have well understood, you want to display one of the names of the
database, by asking a question at the console. Here is a solution. Note
that I have little experience with Ruby, and there are plenty of ways to
do the same thing, especially in Ruby.
class SomeDataProcessing
Person = Struct.new :name, :last_name, :call_name, :age
def self.openOn(p_file)
# this class method is a trick to hide new
# could be more stuff here
new(p_file)
end
def initialize(p_file)
@file = p_file # not necessary if used only once,
loadData(p_file) instead
@persons = {} # or Hash.new
loadData
end
def addPerson
puts "Name of new person ?"
name = gets.chomp
# other data
puts "Age of new person ?"
age = gets.chomp
@persons[name] = Person.new(name, # last_name, call_name,
age)
end
def choose
loop do
puts "Create new ? ( y(es) / l(ist) / n(ame) / q(uit) )"
answer = gets.chomp.slice(0,1)
case answer
when "y"
addPerson
when "l"
listData
when "n"
puts "Name of person ?"
name = gets.chomp
showData(name)
when "q"
exit
else
puts "Please anser y[es], l[ist], n[ame] or q[uit]"
puts ""
end
end
end
def listData
@persons.keys.sort.each {|p| showData(p)}
end
def loadData
File.foreach(@file) do |line|
name, last_name, call_name, age = line.chomp.split(",")
@persons[name] = Person.new(name, last_name, call_name, age)
end
end
def showData(p_name)
person = @persons[p_name]
if person.nil?
then
puts "#{p_name} not in file"
return
end
puts "Name: #{person.name} #{person.last_name}"
puts "Callname: #{person.call_name}"
puts "Age: #{person.age}"
puts
end
end # class SomeDataProcessing
dp = SomeDataProcessing.openOn(“data.txt”)
dp.choose
…>ruby -w show_data22.rb
Create new ? ( y(es) / l(ist) / n(ame) / q(uit) )
y
Name of new person ?
xyzzzzzzzzz
Age of new person ?
99
Create new ? ( y(es) / l(ist) / n(ame) / q(uit) )
l
Name: name lastname
Callname: callname
Age: age
Name: name2 lastname2
Callname: callname2
Age: age2
Name: xyzzzzzzzzz 99
Callname:
Age:
Create new ? ( y(es) / l(ist) / n(ame) / q(uit) )
n
Name of person ?
name2
Name: name2 lastname2
Callname: callname2
Age: age2
Create new ? ( y(es) / l(ist) / n(ame) / q(uit) )
q
Hope that helps.
Bernard