将数组的散列与数组进行比较以查找相似之处

时间:2016-09-18 03:10:59

标签: ruby multidimensional-array associative-array

我试图将选定的animal_id数组与" animal_id"进行比较。 owner_to_animals数组中的对象,因此我可以只列出相关的owner_id。我试图迭代哈希然后只选择在animal_id数组中匹配的animal_id对象,但它打印出animal_id = 20,这不是animal_id数组的一部分。

animal_id = [23, 53, 63]
owners_to_animals = [
  { "owner_id" => 73, "animal_id" => 53 },
  { "owner_id" => 73, "animal_id" => 23 },
  { "owner_id" => 73, "animal_id" => 63 },
  { "owner_id" => 73, "animal_id" => 20 },
  { "owner_id" => 83, "animal_id" => 23 },
  { "owner_id" => 83, "animal_id" => 63 }
]

owners_to_animals.each do |x|
  # puts x
  # x.each do |y|
  for i in animal_id do
    # puts i
    if x.select { |a| a["animal_id"] == i }
      puts x
    else
      puts "no"
    end
  end

  # end

end

我很困惑为什么x会返回:

{"owner_id"=>73, "animal_id"=>53}
{"owner_id"=>73, "animal_id"=>53}
{"owner_id"=>73, "animal_id"=>53}
{"owner_id"=>73, "animal_id"=>23}
{"owner_id"=>73, "animal_id"=>23}
{"owner_id"=>73, "animal_id"=>23}
{"owner_id"=>73, "animal_id"=>63}
{"owner_id"=>73, "animal_id"=>63}
{"owner_id"=>73, "animal_id"=>63}
{"owner_id"=>73, "animal_id"=>20}
{"owner_id"=>73, "animal_id"=>20}
{"owner_id"=>73, "animal_id"=>20}
{"owner_id"=>83, "animal_id"=>23}
{"owner_id"=>83, "animal_id"=>23}
{"owner_id"=>83, "animal_id"=>23}
{"owner_id"=>83, "animal_id"=>63}
{"owner_id"=>83, "animal_id"=>63}
{"owner_id"=>83, "animal_id"=>63}

1 个答案:

答案 0 :(得分:3)

如果没有匹配的话,

select将返回一个空数组,这在Ruby中是一个" truthy"值,因此代码的else分支永远不会被执行。

if []
  puts "true"
else
  puts "false"
end
# Outputs "true"

您想要实现的目标可以在一行中完成:

puts owners_to_animals.select { |x| animal_id.include?(x["animal_id"]) }
# Output:
{"owner_id"=>73, "animal_id"=>53}
{"owner_id"=>73, "animal_id"=>23}
{"owner_id"=>73, "animal_id"=>63}
{"owner_id"=>83, "animal_id"=>23}
{"owner_id"=>83, "animal_id"=>63}