Search code examples
rubymonkeypatching

How might I treat nil values as zero when adding numbers?


I have a method that looks like this:

def calculate_the_thing(hsh)
  hsh[:x] + hsh[:y] + hsh[:z]
end

which takes something like this:

{:x => 5, :y => nil, :z => 2, :a => 5}

I'd like to patch some classes so that when the + method gets a nil value, it treats it as zero. Seems reasonable. How might I do that?


Solution

  • As @jforberg points out, you can just use the #to_i method which will return 0 for nil.

    def calculate_the_thing(hsh)
      hsh[:x].to_i + hsh[:y].to_i + hsh[:z].to_i
    end
    

    Alternatively, you can also define the hash with an automatic default value...

    hsh = Hash.new{0}
    

    But if you have a method that explicitly puts nil as a hash value that will override the default value.