Acing assessments

DIGIT = { A: 1, B: 2, F: 6 } scores1 = [ :A, :A, :A, :A, :A ] scores2 = [ :B, :B, :A, :A, :B ] scores3 = [ :F, :B, :F, :F, :A ] def verdict(scores) scores.map! { |score| DIGIT[score] } average = scores.sum / scores.length if average == 1 puts 'Aced!' elsif average <= 2 puts 'Ok.' else puts 'Uh! Oh!' end end verdict(scores1) # Aced! verdict(scores2) # Aced! verdict(scores3) # Uh! Oh!
Why does scores2 count as aced?

1 Response

On line 21 we call method `verdict` and send in the value of scores2 as an argument. The method starts executing. In the method body we iterate through `scores2` array. On line 9 the `scores.sum` value is 8 and the `scores.length` is 5. Here Ruby performs Integer division, therefore instead of expected float value of `1.6`, the value assigned to variable `average` is `1`. Further in the method we have an `if ` conditional statements where the first condition returns `true` and the method outputs "Aced!".
In order to fix it, instead of Integer division we have to perform Float division. We can execute that by calling Ruby `Float.to_f` method when performing division.
```ruby
average = scores.sum.to_f / scores.length.to_f # 8.0 / 5.0 = 1.6
```

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.