What is number.pred in Ruby?

In Ruby, we use .pred to return the immediate predecessor of a number. When it is called on a number, it returns that number minus 1.

Syntax

number.pred

Parameters

The pred function takes no parameters. It only needs to be called on a number value.

Code

In the code below, the pred function is called on some number values and the returned values are printed on the console.

# create numbers
num1 = 1
num2 = 34
num3 = 4500 # same as 4_500
num4 = 732394
num5 = -2
num6 = -23
num7 = -100
# print value to the console
puts num1.pred
puts num2.pred
puts num3.pred
puts num4.pred
puts num5.pred
puts num6.pred
puts num7.pred

Note: When the pred function is called on a float instead of an integer, an error will be thrown.

# create a float number
floatNumber = 0.5
# print `pred` value to console
puts floatNumber.pred # will throw an error.

Free Resources