ruby string equality
Ruby String Equality
To check for string equality in Ruby, you can use the ==
operator. This operator compares the contents of two strings and returns true
if they are equal, and false
otherwise. Here's an example:
str1 = "Hello"
str2 = "Hello"
if str1 == str2
puts "The strings are equal"
else
puts "The strings are not equal"
end
In this example, the ==
operator is used to compare str1
and str2
. Since both strings have the same content ("Hello"), the condition str1 == str2
evaluates to true
, and the message "The strings are equal" is printed.
It's important to note that the ==
operator checks for content equality, not object identity. This means that two different string objects with the same content will be considered equal. For example:
str1 = "Hello"
str2 = "Hello"
if str1 == str2
puts "The strings are equal"
else
puts "The strings are not equal"
end
In this case, even though str1
and str2
are different objects, they have the same content ("Hello"), so the condition str1 == str2
still evaluates to true
.
If you want to check for object identity (i.e., if two variables refer to the same object), you can use the equal?
method. For example:
str1 = "Hello"
str2 = "Hello"
if str1.equal?(str2)
puts "The variables refer to the same object"
else
puts "The variables refer to different objects"
end
In this example, since str1
and str2
are different objects, the condition str1.equal?(str2)
evaluates to false
, and the message "The variables refer to different objects" is printed.
That's how you can check for string equality in Ruby using the ==
operator and object identity using the equal?
method.