好的,如果我有哈希哈希代表这样的书:
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 :(得分:5)
获取哈希值,然后使用Enumerable#map
从该值(哈希数组)中提取作者:
books = {
"Harry Potter" => {"Genre" => "Fantasy", "Author" => "Rowling"},
"Lord of the Rings" => {"Genre" => "Fantasy", "Author" => "Tolkien"}
}
authors = books.values.map { |h| h["Author"] }
# => ["Rowling", "Tolkien"]
答案 1 :(得分:4)
我会做
Books = {
"Harry Potter" => {"Genre" => 'Fantasy', "Author" => "Rowling"},
"Lord of the Rings" => {"Genre" => 'Fantasy', "Author" => "Tolkien"}
}
authors = Books.map { |_,v| v["Author"] }
# => ["Rowling", "Tolkien"]
答案 2 :(得分: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)