In a bootcamp exercise, we were given this array:
library = [
{
"title" => "Hitchhiker's Guide",
"Author" => "Douglas Adams",
"categories" => [ "comedy", "fiction", "british"]
},
{
"title" => "Pride and Prejudice",
"Author" => "Jane Austen",
"categories" => [ "morality", "fiction", "society", "british"]
},
{
"title" => "Search Inside Yourself",
"Author" => "Chade-Meng Tan",
"categories" => [ "self improvement", "non-fiction", "mindfulness", "business"]
},
{
"title" => "Benjamin Franklin: An American Life",
"Author" => "Walter Isaacson",
"categories" => [ "non-fiction", "history", "founding fathers"]
},
{
"title" => "Glengarry Glen Ross",
"Author" => "David Mamet",
"categories" => [ "play", "fiction", "drama"]
}
]
and we need to make a new hash with the categories as the elements, and the titles as the values.
Was able to figure out how to make a category_hash, but I can't figure out how to append the titles to each category. Here is my code:
category_hash = {}
sub_category = []
library.each do |book|
book["categories"].each do |category|
sub_category << category
end
sub_category.each do |index|
category_hash[index] = "I'm not sure how to append the titles here"
end
end
p category_hash
Can someone help me figure out this step?
"categories"in the elements (hashes) oflibrary; two answers assume "categories" are the strings included in one or more values of "categories" in the elements oflibrary("comedy", "fiction", "british", "morality", "society" and so on). I'm guessing you intended the latter interpretation.