Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Pattern to Indifferently Compare Strings/Symbols for Equality?

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.

like image 513
dliggat Avatar asked Jul 25 '14 17:07

dliggat


2 Answers

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.

like image 69
Matt Avatar answered Oct 14 '22 23:10

Matt


Since Ruby 2.4 You can use match? method

> :abc.match?(/abc/)
=> true
> 'abc'.match?(/abc/)
=> true
like image 31
ToTenMilan Avatar answered Oct 15 '22 00:10

ToTenMilan