测试 Ruby 字符串或符号的字符串相等性(不是对象相等性)的最简洁方法?

我总是这样做来测试 Ruby 中的字符串相等性:

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

这是不测试对象相等性的正确方法吗?

我正在寻找最简洁的方法来测试字符串的基础上的内容。

加上括号和问号,这看起来有点笨拙。

113463 次浏览

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

Doing either

mystring == yourstring

or

mystring.eql? yourstring

Are equivalent.

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.