user94154
user94154

Reputation: 16564

Ruby: Round number down to nearest number based on arbitrary list of numbers

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

Upvotes: 10

Views: 2189

Answers (2)

Mark Byers
Mark Byers

Reputation: 838226

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.

Upvotes: 16

unignorant
unignorant

Reputation: 151

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

Upvotes: 1

Related Questions