On 4 Dec 2016 11:11, "Micky Scandal" <mickyscandal / gmail.com> wrote:


On Sat, Dec 3, 2016 at 4:28 PM, Guillaume Hivert <
guillaume.hivert / outlook.com> wrote:

> (Or even array.sort.reverse!.find { |num| num < limit } will work.)



That's almost exactly what I have except mine's on two lines. does that
make any difference? and i used the bang on reverse and not sort because I
guess I just assumed I only needed it on one of the two? is that not right?
(I did get the right answer with the code as it currently is)


  However, "Return the first number from an Array that is less than a
particular number" doesn't seem to ask for a sorted array. Maybe
array.find { |num| num < limit } is enough?


Seems that way to me.  Note that it says "first number",  not "largest
number".


in this particular case that would be enough but lets say I had this array:
   [13,21,0,7,11,106]   # same array but the 0 and 7 are switched
the correct answer should be 7, but If I ran just the find like that it
would return 0 instead of 7 because it comes across the 0 first. that's why
I sorted and reversed it.



The answer 7 only applies to the array given in the example,  if you start
with a different array you should probably expect a different result. As
written, I'd expect 0.

Consider this approach, which doesn't use #find but solves the problem
using another key word ("first"):

    array.select{|e| e < limit }.first

Also note that bang methods (like #reverse!) sometimes return nil, so be
careful when chaining them.

Cheers
(supressed text/html)
Unsubscribe: <mailto:ruby-talk-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>