{"Genre" => Fantasy, "Author" => "Rowling"}, "Lor-6ren">
gpt4 book ai didi

Ruby 快速从散列的散列中创建一个数组?

转载 作者:数据小太阳 更新时间:2023-10-29 07:45:06 26 4
gpt4 key购买 nike

好吧,如果我有一个散列的散列来表示这样的书:

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)

谁知道这种表情怎么写?非常感谢您收到的任何帮助。

最佳答案

获取哈希值,然后使用 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"]

关于Ruby 快速从散列的散列中创建一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22178446/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com