On Mon, Dec 5, 2016 at 9:38 AM, Andy Jones <Andy.Jones / jameshall.co.uk> wrote:
> It seems as if max_by() deserves a mention here:
>
>     def first_under(array, limit)
>       array.max_by{|e| e < limit ? e : 0 }
>     end
>
> That will get you the highest number in the array less than the limit.

No, this does not work reliably (e.g. when there are only negative
numbers in array).

There are multiple ways to solve this more robustly but if you want to
have only one iteration through the Enumerable (does not need to be an
Array!) then #inject leads to a nice solution:

def max_under(array, limit)
  array.inject nil do |max, i|
    i < limit && (max.nil? || i > max) ? i : max
  end
end

irb(main):011:0> max_under [13, 21, 7, 0, 11, 106], 10
=> 7
irb(main):012:0> max_under [13, 21, 7, 0, 11, 9, 106], 10
=> 9

Kind 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>