Question

Okay, so if I have a hash of hashes to represent books like this:

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

Is there any way that I could concisely get an array of all authors in the books hash? (If the same author is listed for multiple books, I would need their name in the array once for each book, so no need to worry about weeding out duplicates) For example, I would like to be able to use it in the following way:

list_authors(insert_expression_that_returns_array_of_authors_here)

Does anyone know how to make this kind of expression? Thanks very much in advance for any help received.

Était-ce utile?

La solution

Get hash values, then extract authors from that values (arrayes of hashes) using 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"]

Autres conseils

I'd do

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

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

I would do.

     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)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top