A
A
arruah2019-02-06 10:45:23
ruby
arruah, 2019-02-06 10:45:23

How to sort nested hash by average in ruby?

I have a hash like this:

movies = {
  1 "Interstellar" => {
  2 "John" => 10,
  3 "Jack" => 3
  4 },
  5 "Psyho" => {
  6 "Jack" => 9,
  7 "Jane" => 10
  8 },
  9 "Seven" => {
 10 
 11 }
 12 }

You need to find the average rating for each movie and display the list of movies sorted in descending order.
I calculated the average rating like this:
movies.each do |x|
     current_movie = x[0]
    avg_rate = movies[current_movie].values.map.sum.fdiv(movies[current_movie].size)
     if movies[current_movie].empty?
      puts "Rating is not available for #{x[0]}"
     else
     puts "#{x[0]} is rated #{avg_rate.to_s}"
     end
    end

I'm not sure how to sort the output. As I see it, you need to create a new hash, write the data key => value there as movie => avg_rating and do .sort.
Or is there another shorter solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
N. Bekseitov, 2019-02-06
@arruah

sorted_ratings = movies.each_with_object({}) do |(name, votes), hash|
  sum = votes.values.sum
  hash[name] = sum.nonzero? ? sum.to_f / votes.count : 0
end.sort_by(&:last).reverse

sorted_ratings.each do |name, rating|
  if rating.nonzero?
    puts "#{name} is rated #{rating}"
  else
    puts "Rating is not available for #{name}"
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question