Is there an idiomatic Ruby pattern to test two 'strings' for equality that is indifferent to whether the operands are strings or symbols?
I'd like to use some operator to perform this comparison: :abc == 'abc'.to_sym
without the need to normalize the operands to strings or symbols.
The HashWithIndifferentAccess
behaviour in active_support
is a pretty useful analogy for the sort of thing I'm looking for.
If you want to monkey patch the generic functionality in everywhere.
class Object
def to_s_equals? var
self.to_s == var
end
end
As mentioned, only convert symbols to strings, not strings to symbols unless you have a subsequent use for the symbol. You could be more specific and only do that on Symbol
Alternatively you could add something for String and Symbols, but I can't think of a good common name.
class Symbol
def equals_string? var
self.to_s == var
end
end
class String
def equals_symbol? var
self == var.to_s
end
end
Even then equals
isn't quite right, but match
infers a regex. homologous
maybe? (corresponding in structure, but not necessarily function)
I don't think your getting much brevity on to_s ==
. Maybe a bit of clarity enforcing the order you do the comparisons in.
Since Ruby 2.4 You can use match?
method
> :abc.match?(/abc/)
=> true
> 'abc'.match?(/abc/)
=> true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With