如何将对象与数组#ruby进行比较

时间:2018-05-06 04:12:55

标签: json ruby

我在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

它无法正常工作,怎么做?

1 个答案:

答案 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