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?
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?
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
Though there is casecmp
:
0 == s1.casecmp(s2) # strings equal
I personally prefer
s1.downcase == s2.downcase
You can convert the strings to lowercase and then compare
a.downcase == b.downcase
Or, if you prefer, to uppercase
a.upcase == b.upcase
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.