how to sum [{ a: 5, b: 10, c: 15 }, {}, {q: 67}] such the i don't get the "undefined method `values' for nil:nilclass" error in ruby

To sum the values of the keys a, b, and c in each hash element of the array [{ a: 5, b: 10, c: 15 }, {}, {q: 67}] without encountering the "undefined method values' for nil:nilclass" error in Ruby, you can use the fetch` method to handle the case where a hash element doesn't have all the required keys. Here's an example:

main.rb
arr = [{ a: 5, b: 10, c: 15 }, {}, { q: 67 }]

sum = 0
arr.each do |hash|
  sum += hash.fetch(:a, 0) + hash.fetch(:b, 0) + hash.fetch(:c, 0)
end

puts sum
155 chars
9 lines

The code above uses the fetch method to retrieve the values for keys a, b, and c from each hash element. The second argument of fetch specifies a default value to return if the key is not found in the hash. In this case, we set the default value to 0 so that we can safely perform addition even if a key is missing.

This approach ensures that the sum calculation can handle hashes without all the required keys without throwing the "undefined method `values' for nil:nilclass" error.

related categories

gistlibby LogSnag