如何在Ruby中生成自定义案例语句 [英] How to generate custom case statement in Ruby

查看:86
本文介绍了如何在Ruby中生成自定义案例语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编写生成自定义case语句的方法时遇到问题.

I have problem to write method which generate custom case statement.

我的代码:

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])

推荐答案

您可能想为您的问题添加更多细节和上下文,但是如果我理解正确,则可以在不使用案例说明的情况下执行此操作:

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

然后给出结果:

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

这篇关于如何在Ruby中生成自定义案例语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆