hash - Persisting Hashes in Ruby -
i trying solve simple ruby quiz problem , having problem working hashes. when create wallet regular variable loop has no thought bout variable wallet
, when create @wallet
merge not persisted when returned after loop.
i have tried merge!
collect garbage , keeps info previous test.
class coins coinstar = { :h=>50,:q=>25,:d=>10,:n=>5,:p=>1 } def self.make_change(value) homecoming {} if value == 0 coinstar.each |k,v| wallet = hash.new if value >= v wallet.merge(k=>value / v) value = value - (v * (value % v)) end end wallet end end #test run coins.make_change(26) coins.make_change(91) coins.make_change(1) #=>returns # {:p=>1, :q=>1} # {:p=>1, :q=>1, :h=>1} # {:p=>1, :q=>1, :h=>1}
any ideas on how persist hash without collecting info previous test?
to work, need prepare 3 problems.
first, ymonad notes, move wallet = hash.new
before each loop.
second, alter merge
merge!
.
third, alter value = value - (v * (value % v))
value = value % v
.
the first alter needed move wallet scope of method def self.make_change rather scope of each loop.
the sec alter needed want persist info through iterations of each loop (so half dollars, quarters, dimes, nickels, , pennies added).
the 3rd alter needed create sure value equals number of coins remaining (e.g, value 91, v 50, 91 % 50
= 41
91 - (50 * (91 % 50))
= 91 - (50 * 41)
= (91 - 2050)
= -1959
).
ruby hash persistent persist
No comments:
Post a Comment