Answer the question
In order to leave comments, you need to log in
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 }
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
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question