How to check if strings or boolean values are equal in Ruby
Overview
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.
Syntax
op1 == op2
Operands
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.
Return value
This method returns a Boolean value.
Code example
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)
Code explanation
- Lines 2–9: We create the string variables
str1andstr2, the boolean variablesbool1andbool2, the decimal variablesdec1anddec2, and finally the array variablesarr1andarr2. - Lines 12–16: We create the
equalityCheck()method. This method takes two arguments and uses the==operator to compare them and see if they are equal or not. - Lines 19–26: We use the
equalityCheck()method that we created previously to compare the variables we created. Then, we print the results to the console.