Voss Voss - 2 months ago 7
Ruby Question

Comparing a hash of arrays to an array to find similarities

I'm trying to compare the selected animal_id array to the "animal_id" object in the owners_to_animals array so I can have a list of only the relevant owner_id's. I tried to iterate through the hash then only select the animal_id object that matches in the animal_id array but it prints out animal_id=20 which isn't part of the animal_id array.

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


I'm confused as to why x returns:

{"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}

Answer

select will return an empty array if nothing matches, which in Ruby is a "truthy" value, so the else branch of your code never gets executed.

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

What you want to achieve can be done in a single line:

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}
Comments