2014-03-04 36 views
3

好了,所以如果我有哈希散列代表的書是這樣的:Ruby很快就把哈希中的一部分散列掉了?

Books = 
{"Harry Potter" => {"Genre" => Fantasy, "Author" => "Rowling"}, 
"Lord of the Rings" => {"Genre" => Fantasy, "Author" => "Tolkien"} 
... 
} 

有什麼辦法,我可以簡明地得到在書本哈希所有作者的陣列? (如果同一作者列在多本書中,我會在每本書中爲它們命名一次,因此不必擔心刪除重複內容)例如,我希望能夠通過以下方式使用它:

list_authors(insert_expression_that_returns_array_of_authors_here) 

有沒有人知道如何使這種表達?非常感謝所收到的任何幫助。

+0

這也適用:'books.to_s.scan(/ \「Author \」\ s * => \ s * \「(。+?)\」/)。flatten'。不推薦;只是說。 –

回答

5

獲取的哈希值,然後從該值使用Enumerable#map(哈希arrayes)提取作者:

books = { 
    "Harry Potter" => {"Genre" => "Fantasy", "Author" => "Rowling"}, 
    "Lord of the Rings" => {"Genre" => "Fantasy", "Author" => "Tolkien"} 
} 
authors = books.values.map { |h| h["Author"] } 
# => ["Rowling", "Tolkien"] 
+0

太棒了。它永遠不會讓我驚歎我是如何支持社區的。 :D 答案完美無缺,感謝您的快速回復! – user3380049

+0

@ user3380049,歡迎來到Stack Overflow!有些人試圖回答你的問題。如果這對你有幫助,你可以通過[接受答案](http://meta.stackexchange.com/a/5235)告訴社區,這對你最有用。 – falsetru

+0

感謝您的指針! – user3380049

4

我做

Books = { 
      "Harry Potter" => {"Genre" => 'Fantasy', "Author" => "Rowling"}, 
      "Lord of the Rings" => {"Genre" => 'Fantasy', "Author" => "Tolkien"} 
     } 

authors = Books.map { |_,v| v["Author"] } 
# => ["Rowling", "Tolkien"] 
0

我會怎麼做。

 Books = { 
     "Harry Potter" => {"Genre" => 'Fantasy', "Author" => "Rowling"}, 
     "Lord of the Rings" => {"Genre" => 'Fantasy', "Author" => "Tolkien"} 
       } 

    def list_authors(hash) 
     authors = Array.new 
     hash.each_value{|value| authors.push(value["Author"]) } 
     return authors 
    end 


    list_authors(Books)