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?
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.
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.
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.
(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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With