```On Mon, Dec 5, 2016 at 4:22 PM, Andy Jones <Andy.Jones / jameshall.co.uk> wrote:

>> irb(main):015:0> limit = 10; [-1, 20, -2].max_by{|x| x < limit ? x : nil }
>> ArgumentError: comparison of NilClass with -1 failed
>>         from (irb):15:in `each'
>>         from (irb):15:in `max_by'
>>         from (irb):15
>>         from /usr/bin/irb:11:in `<main>'
>
>
>     [1] pry(main)> limit = 10; [-1, -20, -2].max_by{|x| x < limit ? x : nil }
>     => -1

This will fail for the quite common case that there is at least one
value larger or equal the limit among other values.

>     [2] pry(main)> limit = 10; [-1, 20, -2].max_by{|x| x < 10 ? x : -9999999 }
>     => -1

This will fail for arrays where all values are above the limit.

> See my previous answer about my example code not working against all test cases?

It is our task as programmers to recognize reasonable test cases and
code accordingly. I found these cases quite obvious and in no way
arcane. A solution that does not cover common or fairly common cases
should not be propagated IMO.

Enumerable#max_by is just not suited to this kind of problem, because
it requires at the same time to translate invalid values (i.e. above
the limit) to special values to avoid including them in the
calculation of the maximum (ideally of other type, e.g. nil) AND to
translate all inputs to values which can be compared - typically this
is the case for uniform type translation. These are contradicting
requirements and that shows in the test inputs I presented.

If you want to use a max method then you have to reduce to the valid set, e.g.

[-1, 20, -2].select {|x| x < 10}.max

This is quite elegant although it requires two passes through the data
set. For small inputs that most likely does not make a difference. If
inputs can be really large it probably does.

> Please try not to act like an idiot.

I am sorry, I was a jerk when pointing at Array.max_by. I'll try
improving, but I cannot give any guarantees.

>  This is not a competition where you can win points by trying to prove other people are wrong, and I'm not interested in having an argument with you.

The point is to discuss weaknesses of solutions for the learning

> You found an interesting edge case in max_by that I was unaware of.  What a shame we can't have a pleasant discussion about that now...

Well, if you say so.

Regards

robert

--
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can
- without end}
http://blog.rubybestpractices.com/

Unsubscribe: <mailto:ruby-talk-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
```