Averaging

2 views
Skip to first unread message

edberner

unread,
Apr 14, 2008, 9:31:04 AM4/14/08
to Ruby on Rails: Talk
Why can I call this
<td><%= team.players.sum(:misses) %></td>
and this
<td><%= team.players.sum(:misses) %></td>

but this gives me 0 (some do not have 0 for misses)
<td><%= team.players.sum(:hit) /
team.players.sum(:misses) unless team.players.sum(:misses) == 0 %></
td>

Craig Demyanovich

unread,
Apr 14, 2008, 10:13:38 AM4/14/08
to rubyonra...@googlegroups.com
Say hits = 2 and misses = 4. In Ruby, 2/4 = 0. However, 2.0/4.0 = 0.5. Try those expressions in irb.

To solve your problem, you could convert the numbers to floats: hits.to_f / misses.to_f = 2.0 / 4.0 = 0.5.

The docs for Number#divmod might be helpful.
http://www.noobkit.com/show/ruby/ruby/ruby-core/numeric/divmod.html

Craig
Reply all
Reply to author
Forward
0 new messages