Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

I can do that like this:

number >= 1 && number <= 10 

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

like image 992
Backo Avatar asked Jul 30 '11 07:07

Backo


People also ask

How to know if a number is in a range?

A Solution that works for negative numbers alsoIf x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.

How do you check if a value is in a range in JS?

We can use the JavaScript's greater than or equal to and less than or equal to operators to check if a number is in between 2 numbers. Also, we can use the Lodash inRange method to do the same thing.

How do you create a range in Ruby?

Ranges as Sequences Sequences have a start point, an end point, and a way to produce successive values in the sequence. Ruby creates these sequences using the ''..'' and ''...'' range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.


2 Answers

(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 
like image 102
Mario Uher Avatar answered Sep 29 '22 13:09

Mario Uher


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 
like image 29
tybro0103 Avatar answered Sep 29 '22 12:09

tybro0103