How to generate custom case statement in Ruby

人走茶凉 提交于 2019-12-11 19:25:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!