質問

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

役に立ちましたか?

解決

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

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top