Search code examples
rubyenumerable

ArgumentError: comparison of NilClass with 1 failed min_by


I need to find out the minimum of an array without nil.

[{val: 1},{val: nil}].min_by { |v| v[:val] }

gets

ArgumentError: comparison of NilClass with 1 failed min_by

My next approach was:

[{val: 1},{val: nil}].min_by { |v| v[:val] || 0 }

But this returns {:duration=>nil}

I only want to get the minimum value without the nil value - expected 1


Solution

  • [{val: 1},{val: nil}].delete_if { |v| v[:val].nil? }.min_by { |v| v[:val] }
    

    You can use delete_if to exclude array elements matching the block, in your case where the value is nil.