2014-03-04 32 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)