2014-11-05 99 views
0

背景:一個聯盟有很多玩家,其中有很多城鎮。每個城鎮都屬於海洋百分比計算 - Ruby on Rails的

我的問題:

我試圖計算在一定的海洋城鎮的百分比。例如:

<% @alliance.players.each do |p| %> 
    <% p.towns.each do |t| %> 
    <%= t.ocean %> 
    <% end %> 
<% end %> 

這給了我一個給定聯盟的所有Town's Ocean's。輸出將是這樣的:

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 

所以我們有多數:54幾條:44

我怎樣才能計算結果,所以我得到的比例在特定的海洋城鎮,所以我得到的輸出例如:Ocean 54: 83%,Ocean 44: 17%

+1

你不應該在View這樣的計算..做控制器內,然後使用視圖中的變量。我沒有這些數據,所以我不能嘗試,但是你可以使用ActiveRecord方法在數據庫級別完成所有的工作。 – 2014-11-05 16:05:03

+1

或者寫一個幫手。或者更好的是,把這個邏輯推到模型上。 – BroiSatse 2014-11-05 16:06:25

回答

3

如何:

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}%"} 
+0

你可以加入我的聊天嗎? http://chat.stackoverflow.com/rooms/64334/percentage-calculation – 2014-11-05 16:09:52