Closed Whatapalaver closed 6 years ago
Well I've finally managed to get it to work. The sites that I found most useful were: https://stackoverflow.com/questions/21566435/find-all-elements-in-an-array-that-match-a-condition and https://stackoverflow.com/questions/18899868/collect-values-from-an-array-of-hashes
I have been stumped by this question for quite a few hours now and have struggled to find any pointers on Stack Overflow but that might be because I have lost sense of what I'm trying to do and therefore don't have a good search term at all.
The task is select from an array of hashes, the names of people who like either specific sports or specific fruits. The fruits or sports category determined by user input.
I think for the first stage, I need to create a new hash from the array. So that I would then have sorted by category value, the names of people who like it.
eg. for sport: new_array = { "squash" => ["Mary", "Lauren", "Govind"] "cycling" => ["Sam", "Will"] etc
I'm stuck at this stage. I've got some code below which is pretty much a copy of the example in the mastery-curriculum notes. I don't totally understand it and therefore don't understand why it is failing.
Any ideas or suggestions of good terms to search?
def specific_like
people = [ { "name" => "Mary", "sport" => "squash", "fruit" => "blackberry" }, { "name" => "Lauren", "sport" => "squash", "fruit" => "orange" }, { "name" => "Isla", "sport" => "weightlifting", "fruit" => "banana" }, { "name" => "Sam", "sport" => "cycling", "fruit" => "orange" }, { "name" => "Govind", "sport" => "squash", "fruit" => "banana" }, { "name" => "Awad", "sport" => "weightlifting", "fruit" => "kiwi" }, { "name" => "Will", "sport" => "cycling", "fruit" => "blackberry" } ]
puts "Enter what category to search" # sport or fruit category = gets.chomp puts "Enter what value to search for" # any value = gets.chomp
sort_by_category = {}
people.each do |person| category = person[category] if person[category] == nil person[category] = [] end
end puts sort_by_category end
specific_like