ruby - How might I treat nil values as zero when adding numbers? -
i have method looks this:
def calculate_the_thing(hsh) hsh[:x] + hsh[:y] + hsh[:z] end which takes this:
{:x => 5, :y => nil, :z => 2, :a => 5} i'd patch classes when + method gets nil value, treats zero. seems reasonable. how might that?
as @jforberg points out, can use #to_i method return 0 nil.
def calculate_the_thing(hsh) hsh[:x].to_i + hsh[:y].to_i + hsh[:z].to_i end alternatively, can define hash automatic default value...
hsh = hash.new{0} but if have method explicitly puts nil hash value override default value.
Comments
Post a Comment