如何检查一个数字是否包含在一个范围内(在一个语句中) ?

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

我可以这样做:

number >= 1 && number <= 10

但是我想用一句话来表达,我该怎么做呢?

79238 次浏览

(1..10).include?(number) is the trick.

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

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

read here about validates_inclusion_of

or the Rails 3+ way:

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

If it's not part of a validation process you can use #between? :

2.between?(1, 4)
=> true

Enumerable#include?:

(1..10).include? n

Range#cover?:

(1..10).cover? n

Comparable#between?:

n.between? 1, 10

Numericality Validator:

validates :n, numericality: {only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 10}

Inclusion Validator:

validates :n, inclusion: 1..10

In Ruby 1.9 the most direct translation seems to be Range#cover?:

Returns true if obj is between beg and end, i.e beg <= obj <= end (or end exclusive when exclude_end? is true).

In case you wonder how that's different from Range#include?, it's that the latter iterates over all elements of the range if it's a non-numeric range. See this blog post for a more detailed explanation.

Rails 4

if you want it through ActiveModel::Validations you can use

validates_inclusion_of :number, :in => start_number..end_number

or the Rails 3 syntax

validates :number, :inclusion => start_number..end_number

But The simplest way i find is

number.between? start_number, end_number

For accurate error messages on a form submit , try these

validates_numericality_of :tax_rate, greater_than_or_equal_to: 0, less_than_or_equal_to: 100, message: 'must be between 0 & 100'

If you want to check particular number exists in custom array,

As for example I want to know whether 5 is included in list=[1,4,6,10] or not

list.include? 5 => false
list.include? 6 => true