Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.equalsIgnoreCase(...) equivalent in Ruby [duplicate]

Tags:

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?

like image 818
Steve Eynon Avatar asked Jan 24 '14 11:01

Steve Eynon


2 Answers

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
like image 179
SirDarius Avatar answered Nov 06 '22 22:11

SirDarius


Though there is casecmp:

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

I personally prefer

s1.downcase == s2.downcase
like image 33
Aleksei Matiushkin Avatar answered Nov 06 '22 22:11

Aleksei Matiushkin