One of the great things about the Ruby language is how easy it is to extend it’s core. Ruby works by merging your class definiton code with the one in it’s standard library. This allows us to add anything to the core classes without writing a separate class of our own. Let’s put that concept to use.
Conditional statements are part of almost all software we write. They tend to get a bit messy with all the symbols thrown around. How about if our conditional statements looked exactly English like in our code? Would not that be a lot better and make the code easier to read?
Since the “Numeric” class is the parent class of all numbers in Ruby, I am going to extend it to make our conditional statements look a lot neater. But first, here they are without any of our efforts.
if number >= 1 && number <= 50 # do something end if number > 1 && number < 100 # do something end if number == 50 # do something end if number >= 1 # do something end if number <= 100 # do something end
Let’s add a few methods to the “Numeric” class.
class Numeric def less_than value return self < value end def greater_than value return self > value end def equals value return self == value end def less_than_or_equals value return self <= value end def greater_than_or_equals value return self >= value end def exclusively_between min, max return (self > min && self < max) end def inclusively_between min, max return (self >= min && self <= max) end end
Here are all our conditional statements after extending the numeric class:
if number.inclusively_between 1, 50 # do something end if number.exclusively_between 1, 100 # do something end if number.equals 50 # do something end if number.greater_than_or_equals 1 # do something end if number.less_than_or_equals 100 # do something end
You could argue extending the “Numeric” class is bit of an effort but it’s a one time effort. You also need to punch in a few extra keys to write your conditional statements but considering the neatness and legibility it adds to your code, I think it is worth the effort.