问题
I have problem to write method which generate custom case statement.
My code:
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 wish to create method that generete this kind of code, for example:
puts create_case_range(68,[64,69,79,89])
回答1:
You might want to add a bit 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
This then gives the result:
> create_case_range(68, [64,69,79,89])
=> 2
来源:https://stackoverflow.com/questions/18630872/how-to-generate-custom-case-statement-in-ruby