How to check if a number is included in a range (in one statement)? How to check if a number is included in a range (in one statement)? ruby ruby

How to check if a number is included in a range (in one statement)?


(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


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


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

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