How to create custom case register in Ruby

I have a problem writing a method that generates a custom case statement.

My code is:

nr=68
puts case nr
   when 0..64 then "1"
   when 65..69 then "2"
   when 70..79 then "3"
   when 80..89 then "4"
   when 90..Float::INFINITY then "5"
end

I want to create a method that generates this type of code, for example:

puts create_case_range(68,[64,69,79,89])
0
source share
1 answer

You might want to add a little more detail and context to your question, but if I understand correctly, you can do this without a case statement:

def create_case_range(nr, range)
  range = (range | [Float::INFINITY]).sort
  range.index(range.detect { |max| nr <= max }) + 1
end

Then this gives the result:

> create_case_range(68, [64,69,79,89])
=> 2
0
source

Source: https://habr.com/ru/post/1533808/


All Articles