comparing two strings in ruby

41

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 tagged with ruby

~ Asked on 2012-12-11 16:34:50

The Best Answer is


102

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

~ Answered on 2012-12-11 16:45:04


7

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

puts var1 == var2[0]

~ Answered on 2012-12-11 16:36:28


Most Viewed Questions: