casecmp to Compare Strings
Today I learned about casecmp
and casecmp?
to compare strings in ruby.
casecmp
compares the downcase of both strings and returns 1
if the compared string is smaller, -1
if it's larger, and 0
if they are equal (and nil
if they can't be compared).
"hashrocket".casecmp("hashrocket") # => 0
"hashrocket".casecmp("hAsHrOcKeT") # => 0
"hashrocket".casecmp("hashrocket123") # => -1
"hashrocket".casecmp("hashrock") # => 1
"hashrocket".casecmp(123) # => nil
casecmp?
does the same comparison but just returns a boolean.
"hashrocket".casecmp("hAsHrOcKeT") # => true
"hashrocket".casecmp("hashrock") # => false
"hashrocket".casecmp(123) # => nil
h/t Brian Dunn
Tweet