Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby能用散列的一部分快速生成一个数组吗?_Ruby_Arrays_Ruby 1.9.3_Hash Of Hashes - Fatal编程技术网

Ruby能用散列的一部分快速生成一个数组吗?

Ruby能用散列的一部分快速生成一个数组吗?,ruby,arrays,ruby-1.9.3,hash-of-hashes,Ruby,Arrays,Ruby 1.9.3,Hash Of Hashes,好的,如果我有一个散列来表示这样的书: Books = {"Harry Potter" => {"Genre" => Fantasy, "Author" => "Rowling"}, "Lord of the Rings" => {"Genre" => Fantasy, "Author" => "Tolkien"} ... } 有没有什么方法可以让我在图书散列中简洁地得到所有作者的数组?(如果为多本书列出了同一作者,则我需要为每本书在数组中列出他们的名

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

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)

有人知道怎么表达这种意思吗?非常感谢收到的任何帮助。

获取散列值,然后使用以下方法从该值(散列的arrayes)中提取作者:

我愿意

我会的

     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)

好极了对社区的支持一直让我感到惊讶D答案完美,感谢您的快速回复!这同样有效:
books.to\u.scan(/\“Author\”\s*=>\s*\“(.+?)\”/).flatten
。不推荐;只是说说而已。
Books = { 
           "Harry Potter" => {"Genre" => 'Fantasy', "Author" => "Rowling"},
           "Lord of the Rings" => {"Genre" => 'Fantasy', "Author" => "Tolkien"}
        }

authors = Books.map { |_,v| v["Author"] }
# => ["Rowling", "Tolkien"]
     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)