I've just started to learn ruby and this is probably very easy to solve. How do I compare two strings in Ruby?
I've tried the following :
puts var1 == var2 //false, should be true (I think) puts var1.eql?(var2) //false, should be true (I think)
When I try to echo them to console so I can compare values visually, I do this :
puts var1 //prints "test content" without quotes puts var2 //prints ["test content"] with quotes and braces
Ultimately are these different types of strings of how do I compare these two?
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.
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (a == b) is not true. !=
=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.
In order to compare things Ruby has a bunch of comparison operators. The operator == returns true if both objects can be considered the same. For example 1 == 1 * 1 will return true , because the numbers on both sides represent the same value.
Here are some:
"Ali".eql? "Ali" => true
The spaceship (<=>
) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method returns 0 if the strings are identical, -1 if the left hand string is less than the right hand string, and 1 if it is greater:
"Apples" <=> "Apples" => 0 "Apples" <=> "Pears" => -1 "Pears" <=> "Apples" => 1
A case insensitive comparison may be performed using the casecmp method which returns the same values as the <=> method described above:
"Apples".casecmp "apples" => 0
From what you printed, it seems var2
is an array containing one string. Or actually, it appears to hold the result of running .inspect
on an array containing one string. It would be helpful to show how you are initializing them.
irb(main):005:0* v1 = "test" => "test" irb(main):006:0> v2 = ["test"] => ["test"] irb(main):007:0> v3 = v2.inspect => "[\"test\"]" irb(main):008:0> puts v1,v2,v3 test test ["test"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With