Pergunta

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

Foi útil?

Solução

[{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.

Outras dicas

You can also reject the nil value

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

Reject will return a new array, delete_if will only delete the value from the matching block - both is possible. But I think delete_if is more performant for your case.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top