Skip to content

Instantly share code, notes, and snippets.

@alexanderjamesking
Created February 2, 2017 09:23
Show Gist options
  • Save alexanderjamesking/e1419eeab7587cd37bce0db0b227ee16 to your computer and use it in GitHub Desktop.
Save alexanderjamesking/e1419eeab7587cd37bce0db0b227ee16 to your computer and use it in GitHub Desktop.
Ruby - Array of hashes to keyed hash
students = [
{ name: "Bob", cohort: "Nov"},
{ name: "Barry", cohort: "Nov"},
{ name: "Anna", cohort: "Dec"},
{ name: "Igor", cohort: "Dec"},
{ name: "Natalia", cohort: "Feb"}
]
my_hash = {}
students.each { |student|
cohort = student[:cohort]
name = student[:name]
# if the key exists then add to the array that already exists in the hash
if (my_hash.has_key?(cohort))
my_hash[cohort].push(name)
else
# the key doesnt exist so create an array and add it to the hash
new_array = []
new_array.push(name)
my_hash[cohort] = new_array
end
}
puts "My hash:"
puts my_hash
puts "Keys:"
puts my_hash.keys
puts "Loop through and display it:"
my_hash.keys.each { |cohort|
print my_hash[cohort]
puts
}
puts "Loop through each cohort as well to display students:"
my_hash.keys.each { |cohort|
puts "Cohort: #{cohort}"
my_hash[cohort].each { |student_name|
puts "- #{student_name}"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment