Main Content

Is this number between? Does this list include? - Ruby

Archive - Originally posted on "The Horse's Mouth" - 2011-04-18 23:15:09 - Graham Ellis

There's often a requirement in a program to see if one value is between two others, and in most languages you'll write that as as double condition:
  if (n >= 5 && n <= 8) printf("Yesssss!\n");
in C or C++, for example.

Some languages give you further options / methods you can use to test for values between two others - usually they're the object oriented languages where additional operators can be defined as methods. In other words - when the authors of he language ran out of special symbols, they started to use words! Here is a use of the between? method in Ruby:
  if k.between?(5,8)

Another requirement is to see if a value is present in a list / array / collection. And in languages such as C you'll write that as a loop, checking each item of the list in turn and using a break go get out of the loop if and when you find the item you're looking for.

Looking for an item in a list is such a common requirement that many of the object oriented languages have defined methods which let you do the test in a single line, hiding (encapsulating) the loop that's actually still going to be run within the class code. So in Ruby you cab simply write:
  if [2,3,5,6,7].include?(k)

There's a new demonstration of each of these, in the context of a complete program, [here] on our web site. I'm running a private Ruby course this week. Public courses - see [here].