3

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.

user3380049
  • 139
  • 1
  • 10

3 Answers3

5

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"]
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Fantastic. It never ceases to amaze me how supporting the community is. :D Answer works perfectly, thanks for the rapid reply! – user3380049 Mar 04 '14 at 18:22
4

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"]
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
0

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)
Stacked-for-life
  • 196
  • 2
  • 17