我试图将选定的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}
答案 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}