Given:
shipping_costs = { key1: 45, key2: 99, key3: nil, key4: 24 }
What's the cleanest way to get the max of those keys assuming nil = 0?
If I run a straight shipping_costs.values.max
in the Rails console I get this:
ArgumentError: comparison of Fixnum with nil failed
Cleanest way to turn those nils into zeros before running max?
If you want to keep it really concise, you can use shipping_costs.values.compact.max
The compact
method removes all nil
values from an array.
The other answers are also good ideas. However, I'd prefer to reject the values instead of replacing them with numbers. I thinks it's better to know an array only contains nil
values than to guess where a 0 (or whatever value you choose) came from.
I'd go for:
shipping_costs.values.map(&:to_i).max
nil.to_i
is 0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With