General Built-in Methods
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.
print(13 % 3,"\n")print("#{13.divmod(4)}","\n")# we can store the two results as belowq , 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:
for a in [1,2,3].reverseprint(a,"\n")endprint('nib'.reverse())
In the program above:
-
An array passes to the
reverse()
function in thefor
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.
We can convert a string to an array of characters using the split()
method for the given string and display each character using a for loop as follows:
for b in 'nib'.reverse().split('')print(b,"\n")end
Rounding off
This function rounds the provided number into the nearest integer value. For example, the values 3.1 to 3.4 are near 3, and the values 3.5 to 3.9 are near 4.
print('value',"\t",'floor',"\t",'ceiling',"\t",'even-rounded:',"\n")for tentimes in 30...47c = tentimes / 10.0print(c,"\t",(c-0.49).round,"\t",(c+0.49).round,"\t",(c).round,"\n")end
In the program above:
- We use the
range
method to generate values from30
to46
in thefor
loop statement. - We convert these integers to floating-point values through division.
- In the
print()
statement, the program displays each floating-point value along with its floor, ceiling, and rounded approximation in each loop iteration.- Subtracts
0.49
from each floating-point value to display the floor value. - Adds
0.49
to each floating-point value to display the ceiling value. Uses the string\t
, which meanstab
and creates multiple spaces for the tabular form of the output.
- Subtracts
Radix converter
The hex
and bin
methods convert a decimal number to hexadecimal and binary, respectively. The following program demonstrates these methods in an interactive way. It takes a decimal number and converts it to the target radix, as input by the user. The program waits for the following two inputs before it runs:
- The decimal number to be converted.
- The target radix (
2
or16
).
print "Enter source number in decimal: " sourceNum = gets.to_i print "Enter target radix 2 or 16: " targetRadix = gets.to_i if(targetRadix == 2) # Checking the value of targetRadix print((sourceNum).to_s(2),"\n") else if(targetRadix == 16) print((sourceNum).to_s(16),"\n") else print("You have entered a wrong target radix",targetRadix,"\n") end end
In the program above:
- We input two values—a decimal number in the
sourceNum
variable and the target radix in thetargetRadix
variable. - We validate the
targetRadix
to be either2
or16
only. - Then, we display the converted number using the appropriate conversion method.
Note: The prefix
0x
indicates a hexadecimal number, and the prefix0b
indicates a binary number.
Sorting
The sort()
function returns a list of values in ascending order. Non-numeric values are sorted based on their ASCII codes.
Here, we’ll use the sort()
function to write a program that sorts characters of a string based on ASCII codes:
nums = [4,2,5,4]print('Original list of numbers:',nums,"\n")print('Sorted list of numbers:',(nums).sort {|a, b| a <=> b},"\n")print("\n")alphs = 'zigZAG'print('Original string:',alphs,"\n")print('Sorted list of alphabets:',(alphs).chars.sort())
In the program above:
-
We first create an array of integers.
-
We call the
sort()
method in theprint()
statement. -
{|a, b| a <=> b}
is a block that defines a condition for sorting elements in an array. The<=>
operator is called the “comparison operator” and it returns-1
if the element on the left is less than the element on the right,0
if the elements are equal, and1
if the element on the left is greater than the element on the right. -
Then we create a string with a combination of lowercase and uppercase letters.
-
We call the
char.sort()
method in theprint()
statement, which returns an array of alphabetical symbols in ascending order based on their ASCII codes.
The
Conversion methods
In Ruby, we have built-in conversion methods to convert data types.
- The
.to_s
method converts any input into strings. - The
.to_i
method converts any input into an integer. The result contains only the integer at the start; for example, 12a or 12.9 becomes 12, but a12 or .9 becomes 0. - The
.to_f
method converts any input into a floating-point number. The result contains only the number at the start and includes a decimal point; for example, 12a or 12 becomes 12.0, and 12.98a becomes 12.98.
a = 12 # Integerb = 12.5 # Floating-point numberc = "12.5a" # Stringprint(".to_s converts #{a}, #{b}, #{c} into string: #{a.to_s}, #{b.to_s}, #{c.to_s}\n")print(".to_i converts #{a}, #{b}, #{c} into integers: #{a.to_i}, #{b.to_i}, #{c.to_i}\n")print(".to_f converts #{a}, #{b}, #{c} into floating-point numbers: #{a.to_f}, #{b.to_f}, #{c.to_f}\n")