Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我在编写生成自定义案例语句的方法时遇到问题。
我的代码:
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
我希望创建生成这种代码的方法,例如:
puts create_case_range(68,[64,69,79,89])
您可能想为您的问题添加更多细节和上下文,但如果我理解正确,您可以在没有 case 语句的情况下执行此操作:
def create_case_range(nr, range) range = (range | [Float::INFINITY]).sort range.index(range.detect { |max| nr <= max }) + 1 end
然后给出结果:
> create_case_range(68, [64,69,79,89]) => 2