Sam Hill Sam Hill - 25 days ago 6
Ruby Question

Ruby - Cannot sum up hash values

I'm new to Ruby (and programming in general). I have a hash that is using data from an external file, and I'm trying to get the total number of values that are greater than 1500.

Here's my code Actually, I need both the number of entries and the total value of purchase orders over 1500. The external file is just a column of order numbers and a column of prices. I'm sure there is a very simple solution, but like I said I'm a beginner and can't figure it out. Any help would be appreciated. Thanks.

Edit: Here is my code. It's just that last while loop that's causing all the problems. I know that's not the right way to go about it, but I just can't figure out what to do.

myhash={}

file=File.open("Purchase Orders.csv", "r")
while !file.eof
line=file.readline

key,value=line.chomp.split(",")
myhash[key]=value
end

total=0
entries=myhash.length
newtotal=0

myhash.each { |key,value|
total+=value.to_f
}
puts total
puts entries

while value.to_f>1500
myhash.each {|key,value| newtotal+=value.to_f}
end

puts newtotal

Answer

I will rewrite the code in ruby idiomatic way in hope you’ll examine it and find out some hints.

prices = File.readlines("Purchase Orders.csv").map do |line|
  line.chomp.split(",").last.to_f
end # array of prices

total = prices.inject(:+) # sum values
pricy = prices.select { |v| v > 1500 }

pricy_sum = pricy.inject(:+) # sum expensives
pricy_count = pricy.length   # expensives’ size

puts "Total sum is: #{total}"
puts "Total expensives is: #{pricy}"