如何检查一个数字是否包含在一个范围内(在一个语句中)? [英] How to check if a number is included in a range (in one statement)?

查看:31
本文介绍了如何检查一个数字是否包含在一个范围内(在一个语句中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ruby on Rails 3.0.9,我想检查一个数字是否包含在一个范围内.也就是说,如果我有一个变量 number = 5 我想检查 1 <= number <= 10 如果 number 值包含在该范围内.

I am using Ruby on Rails 3.0.9 and I would like to check if a number is included in a range. That is, if I have a variable number = 5 I would like to check 1 <= number <= 10 and retrieve a boolean value if the number value is included in that range.

我可以这样做:

number >= 1 && number <= 10

但我想在一份声明中做到这一点.我该怎么做?

but I would like to do that in one statement. How can I do that?

推荐答案

(1..10).include?(number) 是诀窍.

顺便说一句:如果你想使用 ActiveModel::Validations 来验证一个数字,你甚至可以这样做:

Btw: If you want to validate a number using ActiveModel::Validations, you can even do:

validates_inclusion_of :number, :in => 1..10

阅读这里了解validates_inclusion_of

read here about validates_inclusion_of

或 Rails 3+ 方式:

or the Rails 3+ way:

validates :number, :inclusion => 1..10

这篇关于如何检查一个数字是否包含在一个范围内(在一个语句中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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