I am trying to sum values from a ruby hash but using either inject or reduce does not return the correct answer. It seems as though these methods are overwriting the current value being stored instead of summing them.
My hash look like this:
@test = [
{"total"=>18, "type"=>"buy", "date"=>Thu, 21 Nov 2013, "instrument_code"=>"food"},
{"total"=>92, "type"=>"buy", "date"=>Thu, 14 Nov 2013, "instrument_code"=>"food"},
{"total"=>12, "type"=>"buy", "date"=>Wed, 20 Nov 2013, "instrument_code"=>"drink"},
{"total"=>1, "type"=>"buy", "date"=>Mon, 11 Nov 2013, "instrument_code"=>"food"}
]
Here is my inject code that fails:
def additions_per_security
@test.group_by { |i| i.type }.each do |key, value|
if key == "buy"
value.group_by{ |i| i.date }.each do |key, value|
@sortable_additions[key] = value
end
@sorted_additions = @sortable_additions.sort_by { |key,value| key }
@sorted_additions.shift
@additions_per_security = Hash[@sorted_additions.map { |key, value|
[key, value]
}]
@additions_per_security.each do |key, value|
value.group_by { |i| i.instrument_code }.each do |key, value|
@additions_security[key] = value.inject(0){ |result, transaction|
(result += transaction.total)
}
end
end
end
end
return @additions_security
end
Here is my reduce code that fails:
def additions_per_security
@@test.group_by { |i| i.type }.each do |key, value|
if key == "buy"
value.group_by { |i| i.date }.each do |key, value|
@sortable_additions[key] = value
end
@sorted_additions = @sortable_additions.sort_by { |key,value| key }
@sorted_additions.shift
@additions_per_security = Hash[@sorted_additions.map { |key, value|
[key, value]
}]
@additions_per_security.each do |key, value|
value.group_by { |i| i.instrument_code }.each do |key, value|
@additions_security[key] = value.map { |p| p.total }.reduce(0,:+)
end
end
end
end
return @additions_security
end
I have a hash and I want to sum the totals for all keys except the first date.
I am currently getting the following:
{"drink"=>12.0, "food"=>92}
My expected result will look like this:
{"drink"=>12.0, "food"=>110}
Thanks in advance for any advice.
reducefails. I think with a good refactoring you'll be able to get the bugs out.@testhashis not a hash. If you changed the outer{}to[]it would be an array of hashes; now it is not a Ruby object. Also,reduceandinjectare synonyms. Best to simplify, as well as fix,@testhash, by removing unnecessary hash elements. The date, in particular, is not relevant but likely to cause complications.date(here the last hash in @testhash)". You should also remove 'hash' from the name@testhash. Please edit to clarify.