Reputation: 7941
Background: An Alliance has a lot of Players, which have a lot of Towns. Every Town belongs to an Ocean.
My Problem:
I'm trying to calculate the percentage of Towns in a certain Ocean. E.g.:
<% @alliance.players.each do |p| %>
<% p.towns.each do |t| %>
<%= t.ocean %>
<% end %>
<% end %>
This gives me all the Town's Ocean's
of a given alliance. The output will look like this:
54 54 54 54 54 35 54 54 54 54 54 54 54 54 45 45 45 45 45 45 54 54 54 44 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 44 54 44 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54
So we have the Majority: 54 and Few: 44.
How can i calculate the results so i get the Percentage of Towns in a specific Ocean so i get an output of e.g.: Ocean 54: 83%
, Ocean 44: 17%
.
Upvotes: 0
Views: 2520
Reputation: 44685
How about:
percentages = p.towns.group_by(&:ocean).map {|ocean, towns| [ocean, (towns.count/p.towns.count.to_f * 100).round(0)]}.to_h
perentages.each {|ocean, percentage| puts "Ocean #{ocean}: #{percentage}%"}
Upvotes: 3