...

/

Untitled Masterpiece

Learn to use the predefined utility methods available in Ruby.

Built-in methods

Ruby provides built-in utility methods that make it easier for programmers to perform routine tasks. The best-known built-in methods are .length(), gets, and print().

Let’s explore some commonly used built-in methods.

Quotient and remainder together

The divmod() method computes the remainder after the division of two numbers. It differs from the modulus operator % in that it returns two resulting values and the quotient.

Remember: A method in Ruby might return two or more values.

Let’s use an example program to explore the difference between the divmod() method and the % operator.

Ruby 3.1.2
print(13 % 3,"\n")
print("#{13.divmod(4)}","\n")
# we can store the two results as below
q , r = 13.divmod(4)
print("Quotient: ",q,"\n")
print("Remainder: ",r,"\n")

In the program above:

  • We use % to calculate the remainder.

  • We use built-in divmod() method, which accepts two parameters:

    • The dividend
    • The divisor
  • The function then returns two values:

    • The quotient
    • The remainder

Reverse order

The reverse() method is used to access the elements of an array or string in reverse order. The result of this method can be accessed with the help of a loop. The following code will demonstrate how this method works:

Ruby
for a in [1,2,3].reverse
print(a,"\n")
end
print('nib'.reverse())

In the program above:

  • An array passes to the reverse() function in the for loop statement.

  • Each array element is displayed in reverse order in the body of the loop.

  • Similarly, the reverse() function is used to reverse the given string. ...