D
D
Demigodd2019-05-07 22:10:49
ruby
Demigodd, 2019-05-07 22:10:49

How to optimize and shorten the code (hash parsing in ruby)?

Actually here is a link to the code REPL.it
There is a hash:

[
  {
    part: 'one',
    books: {
      rowling: {book: 'Harry Potter', year: 1997},
      martin: {book: 'Game of Thrones', year: 2011},
    }
  },
  {
    part: 'two',
    books: {
      rowling: {book: 'Harry Potter', year: 1997},
      martin: {book: 'Game of Thrones', year: 2011},
      tolkin: {book: 'The Lord of the Ring', year: 2001}
    }
  },
]

I need to parse in such a way that I get the following result:
# Expect Result Output после uniq и сортировки по author
{:author=>:martin, :book=>"Game of Thrones"}
{:author=>:rowling, :book=>"Harry Potter"}
{:author=>:tolkin, :book=>"The Lord of the Ring"}

Any ideas how to implement this in a shorter and more efficient way?
The function that I wrote, I use as many as 3 iterations over the array ( map , each , each ) and at the end sort_by ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-05-07
@Demigodd

arr
  .reduce({}){|acc, n| acc.update(n[:books])}
  .collect{|k, v| { author: k, book: v[:book] }}
  .sort_by{|n| n[:author]}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question