Sam Hill Sam Hill - 6 months ago 29
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={}"Purchase Orders.csv", "r")
while !file.eof



myhash.each { |key,value|
puts total
puts entries

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

puts newtotal


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|
end # array of prices

total = prices.inject(:+) # sum values
pricy = { |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}"