Art_Vandelay17 Art_Vandelay17 - 1 month ago 8
Ruby Question

I have an issue with my Ruby method I am trying to create

I am trying to execute the following code and I am not getting the response I want. I want set the answer to children in the client details hash. I am pretty sure its because I have a get.chomp in my children method but I am not sure that I can set that response to an integer so I can shovel it into my hash.

# Get following details from client:
# name
# age
# number of children
# decor theme
# handicap
# if handicap ask if they would like wheelchair ramp or elevator.
# Program should also:
# Print the hash back to screen when designer answers all questions
# Give the user the option to update a key. Exit if user says "n." If user enters "key," program should ask for new key value and update key. (Strings have methods to turn them into symbols.)
# Print latest version of hash, exit


def children(response)
until response == "y" || response == "n"
puts "Invalid response, Please enter Y/N only!"
response = gets.chomp.downcase
end
if response == "y"
puts "How many children do you have?"
number_of_children = gets.chomp.to_i
else response == "n"
number_of_children = 0
end
end




client_details = {}

# ---- Driver Code ----

puts "Welcome to the Client Information Form!"

# ---- get the user name ----
puts "Please enter the Clients Full Name:"
client_details[:name] = gets.chomp
# ---- get the user age ----
puts "Please enter #{client_details[:name]} age:"
client_details[:age] = gets.chomp.to_i
# ---- find out if the user has children ----
puts "Does #{client_details[:name]} have any children? (Please enter Y/N only)"
children_input = gets.chomp.downcase.to_s
children(children_input)



client_details[:children] = children(children_input)
p client_details


Here is what happens when I run the code:

'Welcome to the Client Information Form!
Please enter the Clients Full Name:
Art V
Please enter Art V age:
55
Does Art V have any children? (Please enter Y/N only)
y
How many children do you have?
8
How many children do you have?
8
{:name=>"Art V", :age=>55, :children=>8}

Answer

The reason why you get duplicated output is that you are calling the children method twice:

# this is the first time here
children_input = gets.chomp.downcase.to_s
children(children_input)

# and this is the second time here
client_details[:children] = children(children_input)

If you want to only call it once, then you need to save/store the return-value eg:

children_input = gets.chomp.downcase.to_s
num_children = children(children_input)
client_details[:children] = num_children