Today I Learned

hashrocket A Hashrocket project

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

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.