views:

57

answers:

2

Say I have an array of integers:

arr = [0,5,7,8,11,16]

and I have another integer:

n = 6

I need a function that rounds down to the nearest number from the array:

foo(n) #=> 5

As you can see, the numbers do not have a fixed pattern. What's an elegant way to do this?

Thanks

+1  A: 

If you are using relatively small arrays (and so not overly worried about efficiency), then this should work fine:

def down_to_array num, arr
  arr.select{|y| y < num}.sort_by{|z| num-z }.first
end

E.g:

myarr = [0,5,7,8,11,16]
puts down_to_array 6.5, myarr #=> 5
unignorant
Nice answer. I would like just to add this link http://ruby-doc.org/core/classes/Enumerable.html#M003120 which is how you can run a benchmark on sort_by to check if it's a good solution with your arrays.
dierre
+6  A: 

Use select followed by max:

arr = [0,5,7,8,11,16]
puts arr.select{|item| item < 6}.max

Result:

5

This runs in linear time and doesn't require that the array is sorted.

Mark Byers
beautiful. one the the reasons I love Ruby. Many thanks!