What is the shortest way to check string equality (rather than object equality) for Ruby strings or characters?

I always do this to check string equality in Ruby:

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

Is this the right way to do this without checking for equality of objects?

I am looking for the most concise way to test strings based on their contents.

With parentheses and a question mark, this seems a bit awkward.

+59
ruby
Nov 10 '09 at 19:01
source share
2 answers

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

Performance

 mystring == yourstring 

or

 mystring.eql? yourstring 

Are equivalent.

+99
Nov 10 '09 at 19:05
source share

Your sample code has not expanded to part of your topic, namely characters, and so part of the question has remained unanswered.

If you have two lines: foo and bar, and both can be either a string or a character, you can check for equality with

 foo.to_s == bar.to_s 

It’s a bit more efficient to skip string conversions on operands with a known type. Therefore, if foo is always a string

 foo == bar.to_s 

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

Prior to Ruby 2.2, avoid using uncontrolled input strings for comparison (with strings or characters), since characters are not garbage collected, and therefore you can open yourself up for denial of service by running out of resources. Limit the use of characters to the characters you control, i.e. Literals in your code and reliable configuration properties.

Ruby 2.2 introduced garbage collection of characters .

+10
Nov 11 '09 at 11:10
source share



All Articles