Ruby Tuesday – String#casecmp

Today’s Ruby Tuesday covers String#casecmp.

String#casecmp is a kind of oddly named method, as what it does is a case insensitive string comparison.

The return value of String#casecmp is either -1, 0, or 1, depending on if the item casecmp is being called on is less than, equal or greater than the string passed in as an argument.

"foobar".casecmp("FOOBAR")
# => 0
"abcdeft".casecmp("ABCDEFG")
# => 1
"abcdefg".casecmp("ABCDEFG")
# => 0
"A".casecmp("b")
# => -1
"a".casecmp("B")
# => -1
"z".casecmp("A")
# => 1
"Z".casecmp("a")
# => 1
"z" <=> "A"
# => 1
"A" <=> "Z"
# => -1
"a" <=> "Z"
# => 1
"Z" <=> "a"
# => -1

This can be handy if you are trying to match two strings by doing a downcase or upcase on the strings, as well as being more clear about what you are trying to accomplish with the comparision.

You can also take advantage of using String#casecmp if you even need to do sorting of items by their name regardless of case.

["foo", "a", "Z", "Foo", "buzz", "FOO"].sort do |a, b|
  result = a.casecmp(b)
  if (result == 0)
    result = a <=> b
  end
  result
end
# => ["a", "buzz", "FOO", "Foo", "foo", "Z"]

–Proctor

Leave a Reply

Your email address will not be published. Required fields are marked *