[ruby] comparing two strings in ruby

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?

This question is related to ruby

The answer is


Comparison of strings is very easy in Ruby:

v1 = "string1"
v2 = "string2"
puts v1 == v2 # prints false
puts "hello"=="there" # prints false
v1 = "string2"
puts v1 == v2 # prints true

Make sure your var2 is not an array (which seems to be like)


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

var1 is a regular string, whereas var2 is an array, this is how you should compare (in this case):

puts var1 == var2[0]