Two strings or boolean values, are equal if they both have the same length and value. In Ruby, we can use the double equality sign ==
to check if two strings are equal or not.
If they both have the same length and content, a boolean value True
is returned. Otherwise, a Boolean value False
is returned.
op1 == op2
op1
: This is the first operand among the two operands that we want to compare.
op2
: This is the second operand among the two operands that we want to compare.
Note: Operands can be of any type, but they cannot be strings.
This method returns a Boolean value.
In the example given below, we will compare strings, boolean values, and arrays to see if they are equal. We will compare them using the ==
operator.
# create variablesstr1 = "hello"str2 = "HELLO"bool1 = truebool2 = falsedec1 = 45.22dec2 = 34.545arr1 = [2, 4, 6, 8]arr2 = [1, 3, 5, 7]# create our equality check functiondef equalityCheck (a, b)result = (a == b) ? "#{a} and #{b} are equal": "#{a} and #{b} not equal"return resultend# check if strings are equalputs equalityCheck(str1, str2)puts equalityCheck(str1, str1)puts equalityCheck(bool1, bool2)puts equalityCheck(bool1, bool1)puts equalityCheck(dec1, dec2)puts equalityCheck(dec1, dec1)puts equalityCheck(arr1, arr2)puts equalityCheck(arr1, arr1)
str1
and str2
, the boolean variables bool1
and bool2
, the decimal variables dec1
and dec2
, and finally the array variables arr1
and arr2
.equalityCheck()
method. This method takes two arguments and uses the ==
operator to compare them and see if they are equal or not.equalityCheck()
method that we created previously to compare the variables we created. Then, we print the results to the console.