Ruby 范围:case 语句中的运算符 [英] Ruby range: operators in case statement

查看:50
本文介绍了Ruby 范围:case 语句中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查 my_number 是否在某个范围内,包括更高的值.

I wanted to check if my_number was in a certain range, including the higher Value.

在 IF 语句中,我只需使用 "x > 100 && x <= 500"

In an IF Statement I'd simply use "x > 100 && x <= 500"

但是我应该在 Ruby 案例(开关)中做什么?

But what should I do in a Ruby case (switch)?

case my_number
when my_number <= 500
    puts "correct"
end

不起作用.

标准范围不包括如果 my_number 正好是 500 的情况,而且我不想添加第二个when",因为我必须写双内容

The standard Range doesn't include the case if my_number is exactly 500, and I don't want to add the second "when", as I would have to write double Content

case my_number
# between 100 and 500
when 100..500
    puts "Correct, do something"
when 500
    puts "Correct, do something again"
end

推荐答案

它应该像你说的那样工作.下面的 case 构造包括值 500.

It should just work like you said. The below case construct includes the value 500.

case my_number
# between 100 and 500
when 100..500
    puts "Correct, do something"
end

所以:

case 500
  when 100..500
    puts "Yep"
end

将返回是的

或者,如果值正好 500,您要执行单独的操作吗?

Or would you like to perform a separate action if the value is exactly 500?

这篇关于Ruby 范围:case 语句中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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