我正在尝试执行以下代码,但我没有得到我想要的响应。我想在客户端详细信息哈希中设置孩子的答案。我很确定它是因为我的子方法中有一个get.chomp但是我不确定我是否可以将该响应设置为整数,所以我可以将它拖到我的哈希中。
# 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
以下是我运行代码时会发生的事情:
'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}
答案 0 :(得分:2)
您获得重复输出的原因是您正在调用children
方法两次:
# 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)
如果您只想调用一次,则需要保存/存储返回值,例如:
children_input = gets.chomp.downcase.to_s
num_children = children(children_input)
client_details[:children] = num_children