I have a statistics module for my library class that shows the most popular books and top readers
module Statistics
def top_reader
orders_grouped = orders.group_by(&:reader)
tab = orders_grouped.max_by(3) { |_k, v| v.count }.map(&:first)
puts "#{tab.map(&:name).join(', ')} - are the top readers"
end
def top_book
orders_grouped = orders.group_by(&:book)
tab = orders_grouped.max_by(2) { |_k, v| v.count }.map(&:first)
puts "#{tab.map(&:title).join(', ')} - are the top books"
end
end
That's how i get top reader and top book I need to get amount of unique readers of the top book now, i tried to do it this way but it's not working correctly and the code are not very clean
def top_book_readers
puts @orders.select { |order| books.include? order.book }.uniq(&:reader).size
end
Expected result is just the amount of unique readers that purchased top book
Edit:
def top_book_readers
orders_grouped = orders.group_by(&:book)
top_orders_grouped = orders_grouped.max_by(1) { |_k, v| v.count }
top_orders_grouped.each do |book, orders|
num_readers = orders.map(&:reader).uniq.count
puts "#{book.title} has #{num_readers} readers"
end
end
This works now, number of readers of top books are also configurable
top_bookmethod?@orders.group_by { ... }.count { |_,v| v.size == 1 }.