从Hash中全部展示

时间:2015-09-25 11:40:27

标签: ruby hash

我正在创建员工目录,并希望让用户搜索特定员工。我希望有一个选项,当用户键入A时,它会显示“员工”的完整列表。

到目前为止,这是我的编码方式:

person = Hash.new()
person["John Doe"] = "Active"
person["Jane Doe"] = "Terminated"
person["Jimmy Doe"] = "Active"
person["Leslie Doe"] = "Terminated"
person.each do |key, value|
  puts "Enter the name of the employee, press 'A' for full list of employees."
  answer = gets.chomp!
  if value == "Terminated"
    puts "#{key} is a Terminated employee"
  elsif value == "Active"
    puts "#{key} is an Active employee"
  else
    puts "#{answer} is not an employee"
  end
end

它返回Enter employee name,但它循环通过,如果它不是员工,则返回完整列表,如:

Enter the name of the employee, press 'A' for full list of employees.
 John Doe
John Doe is an Active employee
Enter the name of the employee, press 'A' for full list of employees.
 active
Jane Doe is a Terminated employee
Enter the name of the employee, press 'A' for full list of employees.
 Jane Doe
Jimmy Doe is an Active employee
Enter the name of the employee, press 'A' for full list of employees.
 d
Leslie Doe is a Terminated employee
=> {"John Doe"=>"Active", "Jane Doe"=>"Terminated", "Jimmy Doe"=>"Active", "Leslie Doe"=>"Terminated"}

为什么我的输入被忽略了,我该如何解决这个问题?我是否必须定义A

1 个答案:

答案 0 :(得分:1)

不确定为什么你有each循环。

person = {
  "A" => "Full List",
  "John Doe" => "Active",
  "Jane Doe" => "Terminated",
  "Jimmy Doe" => "Active",
  "Leslie Doe" => "Terminated",
}
while true
  puts "Enter the name of the employee, press 'A' for full list of employees."
  answer = gets.chomp
  case person[answer]
  when "Full List"  then puts person.keys
  when "Terminated" then puts "#{answer} is a Terminated employee"
  when "Active"     then puts "#{answer} is an Active employee"
  else                   puts "#{answer} is not an employee"
  end
end