Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to check if strings or boolean values are equal in Ruby

okwudili onyejiaku

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 variables
str1 = "hello"
str2 = "HELLO" 
bool1 = true
bool2 = false
dec1 = 45.22
dec2 = 34.545
arr1 = [2, 4, 6, 8]
arr2 = [1, 3, 5, 7]

# create our equality check function
def equalityCheck (a, b)
    result = (a == b) ? "#{a} and #{b} are equal"
                : "#{a} and #{b} not equal"
    return result
end

# check if strings are equal
puts 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)
Compare operand values to see if they are equal or not

Code explanation

  • Lines 2–9: We create the string variables str1 and str2, the boolean variables bool1 and bool2, the decimal variables dec1 and dec2, and finally the array variables arr1 and arr2.
  • 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.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring