我试图比较所选的animal_id数组到owners_to_animals数组中的"animal_id"对象,这样我就可以有一个只包含相关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}
select
将返回一个空数组,如果没有匹配,这在Ruby中是一个" true "值,所以你的代码的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}