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

后端 未结 2 1868
深忆病人
深忆病人 2021-02-01 11:30

I always do this to test string equality in Ruby:

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

Is this is the corre

相关标签:
2条回答
  • 2021-02-01 12:04

    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.

    0 讨论(0)
  • 2021-02-01 12:12

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

    Doing either

    mystring == yourstring

    or

    mystring.eql? yourstring

    Are equivalent.

    0 讨论(0)
提交回复
热议问题