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

后端 未结 2 1867
深忆病人
深忆病人 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.

提交回复
热议问题