Signup/Sign In

Range in Ruby

Ranges are a sequence of data. For example, numbers 0 through 9 are a range. Letters a through z are a range. We can also define our own range.

The syntax for defining range is startvalue..endvalue

Example : 0..9 is a range that contains values from 0 through 9. Similarly 'a'..'z' is also a range with all the alphabets in it.

You can also create your own range like 'aab'..'aae' it contains values aab, aac, aad, aae.

Range example in ruby

Range is a flexible data type in Ruby. We can also call methods on range once it is defined.

Range  methods in ruby - min, max, include?

Ruby: Methods for Range data type

  • include() method is used to check whether the particular element is present in the range or not. If the element is present in the range, it returns true else it returns false.
  • min() method returns the minimum element of the range.
  • max() method returns the maximum element of the range.
  • each method is used to loop around a range and print all the elements of a range on the shell output.

    We can display each element/member of the range like this :

    letters.each { |letter| print(letter) }

    Accessing elemetns of Range in Ruby

    In the above code, each member of the range 'a'..'z' stored in variable letters is copied to the variable letter in each iteration. This is done by using the symbol ||. Then, we can do whatever we want to do with that value. Here, we have just printed the values in the variable letter. Ranges are commonly used as conditions in loops.

  • There is also another useful operator called case equality operator (===). Using this operator, we can determine that whether any particular element is present in the given range or not. If the element is present in the range it returns true, else returns false.

    equality operator on Ranges in Ruby

    Here the element 'c' is present in the variable letters, so it returns true. In the same way, digits is a variable that contains range from 0 through 9, and we are checking whether 100 is of the range using the case equality operator, it returns false indicating that 100 doesn't belong to this range.