/ HOW-TO

How to Check if value is included in between the range?

There are many ways of doing the same thing in Ruby. How to check if a number is between the two values?

Available Methods

You can check if value is in the range by use of following methods,

between
member
include

These methods can be implemented as follows,

Let us initialize three numbers as follows,

Sample Usage

a, b, c = 10,14,20
b.between?(a,c) # returns true/false. here true
(a..c).member?(b) # returns true/false. here true
(a..c).include?(b) # returns true/false. here true

But, I would suggest using between? than member? or include?

The reason behind preferring between that other two is Performance,

Benchmark Performance

Suppose, we measure their Benchmarking performance as follows,

Here, we just have called the block with between, member, include significant number(1000000) of times to check the performance of these methods.

You might see there is no major difference. But, if you want to know why such difference is seen then you may refer the source of between, member, include methods and understand why they behave differently.

Conclusion

Use between rather than using member or include just for the performance optimization as explained above.

akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee