Most concise way to test string equality (not object equality) for Ruby strings or symbols?

Ruby

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

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

Doing either

mystring == yourstring

or

mystring.eql? yourstring

Are equivalent.

Solution 2 - Ruby

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

But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.

Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.

Ruby 2.2 introduced garbage collection of symbols.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBryan LockeView Question on Stackoverflow
Solution 1 - RubyJasonWyattView Answer on Stackoverflow
Solution 2 - RubysheldonhView Answer on Stackoverflow