How can I find the greatest value in a hash that does not exceed a certain value?

advertisements

I'm using Ruby 2.4. I have a hash, whose values are all numeric and waht's more, unique. How do I write an expression to figure out the largest value in the hash that is not greater than a certain number, call it max? I tried

2.4.0 :001 > my_hash = {"a" => 3, "b" => 5, "c" => 8, "d" => 12}
 => {"a"=>3, "b"=>5, "c"=>8, "d"=>12}
2.4.0 :002 > my_hash.values
 => [3, 5, 8, 12]
2.4.0 :004 > my_hash.values.detect{ |a| a < max }
 => 3

but this is returning the smallest number, whereas in the above example, I'd expect the result to be 11.


my_hash.values.select{ |a| a < max }.max