我在Json语言中有这样的数组:
{"id" => "cat", "name" => "Kitty"}, {"id" => "dog", "name" => "Pop"}
我想与输入的对象名称进行比较
@pet =ARGV[0]
my_list.each do |list|
if list[name] == @pet
puts " The ID of pet: #{"id"} "
end
end
它无法正常工作,怎么做?
答案 0 :(得分:1)
例如,my_list
等于:
my_list = [{"id" => "cat", "name" => "Kitty"}, {"id" => "dog", "name" => "Pop"}]
然后,您可以使用Enumerable#find
找到相关值:
@pet = ARGV[0]
my_list = [{"id" => "cat", "name" => "Kitty"}, {"id" => "dog", "name" => "Pop"}]
pet_object = my_list.find { |object| object["name"] == @pet }
puts " The ID of pet: #{pet_object["id"]} " if pet_object
或者您可以修改您的代码,这也适用:
@pet = ARGV[0]
my_list = [{"id" => "cat", "name" => "Kitty"}, {"id" => "dog", "name" => "Pop"}]
my_list.each do |list|
if list["name"] == @pet
puts " The ID of pet: #{list["id"]} "
end
end