Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Finding max of array that may contain nil

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?

like image 966
Jamon Holmgren Avatar asked Nov 09 '12 23:11

Jamon Holmgren


2 Answers

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.

like image 72
toniedzwiedz Avatar answered Oct 03 '22 19:10

toniedzwiedz


I'd go for:

shipping_costs.values.map(&:to_i).max 

nil.to_i is 0.

like image 45
Shadwell Avatar answered Oct 03 '22 18:10

Shadwell