dynamically create a hash in ruby -
i sure question has been asked before, research still hasn't led me conclusive answer. trying create standard key value pair in loop.
the code below iterates expected, storing last value. understand why, because overwriting delivery_hash
variable each time use of =
. tried using shovel operator have used arrays, didn't work.
def calculate_job_delivery_costs delivery_hash = {} delivery_cost_scopes.each |scope| delivery_hash = { scope => job_delivery_costs.send(scope).inject(0) { |total, item| (total + item.cost_per_unit * item.hour_count) * item.quantity } } end delivery_hash end
my desired output
"foo" => 234.32, 'bah' => 345.76, 'baz' => 33.87
well, 1 thing stop blowing away variable, , use hash created in first place:
def calculate_job_delivery_costs delivery_hash = {} delivery_cost_scopes.each |scope| delivery_hash[scope] = job_delivery_costs.send(scope).inject(0) |total, item| (total + item.cost_per_unit * item.hour_count) * item.quantity end end delivery_hash end
or, simpler, build hash individual results:
def calculate_job_delivery_costs delivery_hashes = delivery_cost_scopes.map |scope| cost = job_delivery_costs.send(scope).inject(0) |total, item| (total + item.cost_per_unit * item.hour_count) * item.quantity end [scope, cost] end hash[delivery_hashes] end
Comments
Post a Comment