7

I want to test 2 strings for equality in Ruby in a case insensitive manner.

In languages, such as Fantom, you simply write:

string1.equalsIgnoreCase(string2)

What's the idiomatic way to do this in Ruby?

Steve Eynon
  • 4,979
  • 2
  • 30
  • 48

4 Answers4

16

You can use casecmp

"Test".casecmp("teST")
=> 0

"Test".casecmp("teST2")
=> -1

So to test for equality, you can do:

if str.casecmp(str2).zero?
  # strings are equal
end
SirDarius
  • 41,440
  • 8
  • 86
  • 100
4

Though there is casecmp:

0 == s1.casecmp(s2) # strings equal

I personally prefer

s1.downcase == s2.downcase
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
1

You can convert the strings to lowercase and then compare

a.downcase == b.downcase

Or, if you prefer, to uppercase

a.upcase == b.upcase
Zero Fiber
  • 4,417
  • 2
  • 23
  • 34
  • 1
    While this solution is quite obvious, converting both objects for a simple comparison... just seems a bit over-the-top for me. – Steve Eynon Jan 28 '14 at 11:52
1

You can use String#match method :

s = "Test"
s.match(/teST/i) # => #<MatchData "Test">
s.match(/teST2/i) # => nil

Remember in Ruby all objects are has the truth value, except nil and false. So you can use this trick also to perform conditional testing.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317