Reputation: 796
I have a file.txt
with a float value on each line:
23.45
12.01
15
900.6543
I want to get the mean/average of these values, so I read them text. Here's my script.rb
:
#!/usr/bin/ruby
require 'bigdecimal'
require 'bigdecimal/util'
array = IO.readlines 'file.txt'
array.map(&:to_f)
numerator = array.reduce(0) { |a, v| a + v }
denominator = array.count
mean = numerator.to_f / denominator.to_f
puts mean
I get the following error with ruby script.rb
:
Traceback (most recent call last):
4: from list2.rb:7:in `<main>'
3: from list2.rb:7:in `reduce'
2: from list2.rb:7:in `each'
1: from list2.rb:7:in `block in <main>'
list2.rb:7:in `+': String can't be coerced into Integer (TypeError)
Any suggestions?
Upvotes: 0
Views: 221
Reputation: 36620
When you used array.map(&:to_f)
you created a new array of floats... that you did nothing with. You either want to assign that to a variable and use it, or use #map!
to modify array
.
array.map!(&:to_f)
Upvotes: 1