從不同陣列的散列的創建與元素散在訓練營練習中,我們在獲得這個數組:紅寶石
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"]
}
]
,我們需要與類別爲元素的新哈希值,和標題作爲價值。
能夠弄清楚如何製作category_hash
,但我無法弄清楚如何將標題附加到每個類別。這裏是我的代碼:
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
有人可以幫我弄清楚這一步嗎?
您需要澄清(與編輯)你的意思是「...與類別作爲元素...」。首先,你的意思是「鑰匙」而不是「元素」。你會看到並非所有答案都以相同的方式解釋。迄今爲止,一個答案假設「類別」是與「庫」的元素(散列)中的鍵「類別」相關聯的值;兩個答案假定「類別」是包含在「圖書館」元素(「喜劇」,「小說」,「英國」,「道德」,「社會」等)中的一個或多個「類別」 。我猜你的意圖是後一種解釋。 –