tags:

views:

142

answers:

2

I always do this to test string equality in Ruby:

if mystring.eql?(yourstring)
 puts "same"
else
 puts "different"
end

Is this is the correct way to do this without testing object equality?

I'm looking for the most concise way to test strings based on their content.

With the parentheses and question mark, this seems a little clunky.

+5  A: 

According to http://www.techotopia.com/index.php/Ruby_String_Concatenation_and_Comparison

Doing either

mystring == yourstring

or

mystring.eql? yourstring

Are equivalent.

JasonWyatt
This is correct. The identity comparator is `equal?`.
Chuck
A: 

Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.

If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with

foo.to_s == bar.to_s

It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string

foo == bar.to_s

And if foo is always a symbol

foo == bar.to_sym

sheldonh
`foo.intern == bar.intern` would be better — interning a string is more efficient on average than creating a string from a symbol. (If a given string has been previously interned, it just returns the symbol.)
Chuck
Excellent, thanks for taking the time to add this.
sheldonh