Ruby example

How to convert a string to lowercase in Ruby

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Call downcase: "Hello World".downcase returns "hello world", and upcase goes the other way. Both return a new string. The bang versions (downcase!, upcase!) change the string in place but return nil when nothing changed, so never use their return value. To compare two strings ignoring case, use a.casecmp?(b).

Ruby's case methods are downcase, upcase, swapcase and capitalize, where Python has lower() and upper() and JavaScript has toLowerCase(). They are simple to call but carry three traps: the bang versions return nil when the string was already in the right case, capitalize lowercases everything after the first letter, and the popular one-liners for capitalizing every word change the spacing or break on apostrophes. The sections below cover the four methods, the bang versions, comparing without regard to case, capitalizing the first letter, capitalizing every word, and Unicode text such as ß and the Turkish dotless i, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1downcase, upcase, swapcase and capitalizeRecommended

downcase returns a copy of the string with every letter in lowercase, upcase a copy in uppercase, swapcase flips each letter, and capitalize upcases the first character and lowercases the rest. None of them changes the original string, and only letters change: digits, spaces and punctuation stay as they are. Symbols have the same four methods. The usual reason to call downcase is to normalize input before you compare it, store it or use it as a hash key.

downcase_upcase.rb
title = "Hello World"

puts title.downcase
puts title.upcase
puts title.swapcase
puts title.capitalize

# The original is unchanged: each call returns a new string
puts title

# Only letters change; digits and punctuation stay
puts "Order #42: SHIPPED!".downcase

# Symbols have the same methods
p :Ready.downcase

# Normalize input before using it as a key
prices = { "apple" => 3, "pear" => 5 }
choice = "APPLE"
p prices[choice]
p prices[choice.downcase]

Output

The four calls print hello world, HELLO WORLD, hELLO wORLD and Hello world, and title still prints Hello World afterwards. Note that capitalize turned World into world: it is not a "first letter only" method (section 4 shows that). The hash lookup with "APPLE" gives nil because hash keys are case-sensitive; after downcase it finds 3.

2downcase! and upcase! return nil when nothing changed

Each method has a bang version (downcase!, upcase!, swapcase!, capitalize!) that changes the string itself instead of returning a copy. The return value is the catch: it is the string when something changed and nil when the string was already in that case. Code like name = input.downcase! works in testing with mixed-case input and then sets name to nil the first time someone types in lowercase. Chaining another call onto a bang method fails the same way. Call the bang method on its own line, or use the plain method when you want a value.

bang_returns_nil.rb
name = "ruby"
p name.upcase!   # something changed: returns the string
p name
p name.upcase!   # already uppercase: returns nil
p name

# The classic bug: keeping the return value
word = "hello"
result = word.downcase!
p result

# Chaining breaks the same way
begin
  "hello".downcase!.strip
rescue => e
  puts "#{e.class}: #{e.message}"
end

# Fix: the plain method returns the value every time
p "hello".downcase

# Or call the bang method on its own line
word = "HELLO"
word.downcase!
p word

# The nil is useful when you want to know if it changed
input = "LOUD"
puts "was not lowercase" if input.downcase!

# A frozen string can't be changed in place
frozen = "Hi".freeze
begin
  frozen.upcase!
rescue => e
  puts "#{e.class}: #{e.message}"
end

Output

The first upcase! prints "RUBY"; the second, on a string that is already uppercase, prints nil while name stays "RUBY". "hello".downcase! returns nil for the same reason, so chaining .strip onto it raises NoMethodError: undefined method 'strip' for nil. Under # frozen_string_literal: true every literal is frozen, and the bang methods raise FrozenError as in the last line; the plain methods always work.

3Compare strings ignoring case: casecmp?

a.casecmp?(b) returns true when the two strings are equal ignoring case, and uses full Unicode case folding. casecmp (no question mark) is the older method: it returns -1, 0 or 1 like <=>, which makes it useful for sorting, but it only folds the ASCII letters A to Z. Both return nil rather than false when the argument is not a string. a.downcase == b.downcase also works and is what you will see in older code; it builds two new strings to compare. For a pattern, add the i flag to a regex. To search an array ignoring case, see checking if an array contains a value.

casecmp.rb
answer = "YES"

# casecmp? returns true or false
p answer.casecmp?("yes")
p answer.casecmp?("no")

# casecmp returns -1, 0 or 1, like <=>
p "apple".casecmp("BANANA")
p "apple".casecmp("APPLE")
p "cherry".casecmp("Banana")

# Both return nil for a non-string
p "1".casecmp?(1)

# downcase on both sides gives the same answer
p answer.downcase == "yes"

# casecmp folds only A-Z; casecmp? folds all letters
p "ÉCOLE".casecmp("école")
p "ÉCOLE".casecmp?("école")

# Sorting ignoring case
words = ["banana", "Cherry", "apple"]
p words.sort
p words.sort_by(&:downcase)
p words.sort { |a, b| a.casecmp(b) }

# Regex with the i flag, also in case/when
p "Ruby on Rails".match?(/rails/i)
case answer
when /\Ay(es)?\z/i then puts "confirmed"
end

Output

"ÉCOLE".casecmp("école") prints -1, not 0, because casecmp leaves É alone, while casecmp? says true. Plain sort puts "Cherry" first because every uppercase ASCII letter sorts before every lowercase one; sort_by(&:downcase) gives the dictionary order ["apple", "banana", "Cherry"]. Watch out for the nil from "1".casecmp?(1): it is falsy, so an if treats it as a mismatch, but == false does not.

4Capitalize only the first letter

capitalize upcases the first character and lowercases the rest, so "iPhone sales" becomes "Iphone sales". To upcase the first character and leave the rest alone, replace just that character with sub: sub(/\A./) { it.upcase }, where \A anchors at the start of the string. Indexing, as in s[0].upcase + s[1..], does the same but crashes on an empty string. Use . rather than \w in the pattern: in Ruby, \w matches only ASCII letters, digits and underscore. Rails adds upcase_first through ActiveSupport; plain Ruby does not have it.

first_letter.rb
title = "iPhone sales"

# capitalize lowercases everything after the first letter
p title.capitalize

# Upcase the first character, keep the rest
p title.sub(/\A./) { it.upcase }
p title.sub(/\A./, &:upcase)
p title[0].upcase + title[1..]

# On an empty string, sub does nothing; indexing crashes
p "".sub(/\A./, &:upcase)
begin
  ""[0].upcase + ""[1..]
rescue => e
  puts "#{e.class}: #{e.message}"
end

# \w is ASCII only, so it skips an accented first letter
p "élan".sub(/\A\w/, &:upcase)
p "élan".sub(/\A./, &:upcase)

# The first letter, even after a quote
p '"quoted" text'.sub(/[[:alpha:]]/, &:upcase)

# Lowercase only the first character
p "HTTPS link".sub(/\A./, &:downcase)

Output

capitalize prints "Iphone sales"; the three other forms keep the capital P and print "IPhone sales". On "", ""[0] is nil, which raises NoMethodError: undefined method 'upcase' for nil, while sub just returns "". The \w pattern leaves "élan" unchanged because é is not an ASCII word character; . gives "Élan". The [[:alpha:]] class matches any letter, so it skips the leading quote. The it block parameter is Ruby 3.4 and later; &:upcase works on every version.

5Capitalize every word

Ruby has no built-in title case (Rails' titleize comes from ActiveSupport, and Python's title() has no plain Ruby equivalent). The answer most people find is split.map(&:capitalize).join(" "). It has two side effects: capitalize lowercases the rest of each word, so mcDonald becomes Mcdonald, and split with join collapses runs of spaces into one. gsub(/\b\w/) keeps the spacing but treats an apostrophe as a word break. Matching the first character after the start or a space, (?<!\S)\S, avoids all three problems.

every_word.rb
text = "the  mcDonald's   menu"

# The common answer: lowercases the rest, collapses spaces
p text.split.map(&:capitalize).join(" ")

# gsub with capitalize keeps spaces, still lowercases
p text.gsub(/\S+/, &:capitalize)

# \b\w keeps everything else but breaks on the apostrophe
p text.gsub(/\b\w/, &:upcase)

# Upcase the first character after the start or a space
p text.gsub(/(?<!\S)\S/, &:upcase)

# Also after a hyphen
p "jean-luc   picard".gsub(/(?<![^\s-])[[:alpha:]]/, &:upcase)

Output

The split version prints "The Mcdonald's Menu" with single spaces and a lowercase d. \b\w produces McDonald'S, because the s after the apostrophe starts a new "word". The lookbehind (?<!\S) means "not preceded by a non-space character", so only characters at the start or after whitespace change, giving "The McDonald's Menu". If your input may be all caps and you want Mcdonald-style output, the capitalize versions are the right choice; pick the one that matches the data you have.

6Unicode: ß, accents and the Turkish i

Since Ruby 2.4 the case methods follow Unicode rules, so accented letters convert like any other. Some mappings are not one to one: ß uppercases to SS, and the result can be longer than the input. The methods take an option: :fold (for downcase) applies Unicode case folding, the form meant for comparing rather than displaying; :ascii changes only A to Z; and :turkic uses the Turkish and Azeri rules for the dotted and dotless i. The old tr("A-Z", "a-z") idiom is ASCII-only too.

unicode_case.rb
# Accented letters convert like any other
p "ÉCOLE".downcase
p "straße".upcase
p "ß".upcase.length

# STRASSE lowercases to strasse, not back to straße
p "straße".downcase == "STRASSE".downcase

# :fold is for comparing; casecmp? folds the same way
p "straße".downcase(:fold)
p "straße".downcase(:fold) == "STRASSE".downcase(:fold)
p "straße".casecmp?("STRASSE")

# :ascii (and tr) change only A-Z
p "ÉCOLE".downcase(:ascii)
p "ÉCOLE".tr("A-Z", "a-z")

# :turkic: I and dotless ı, İ and dotted i
p "ISTANBUL".downcase
p "ISTANBUL".downcase(:turkic)
p "istanbul".upcase(:turkic)

# A capital dotted İ lowercases to two characters
p "İ".downcase.length

Output

"straße" uppercases to "STRASSE", but downcase on both spellings gives different strings, so the plain == check prints false. With :fold both become "strasse" and compare equal, and casecmp? agrees. :ascii and tr both leave the É in "École". In Turkish, I lowercases to the dotless ı and i uppercases to the dotted İ, which is what :turkic prints; without it you get "istanbul". Because "İ".downcase has length 2 (an i plus a combining dot), don't assume a case change keeps string lengths or indexes.

7Which should you use?

MethodChanges the originalGotchaBest for
s.downcase / s.upcaseNo, returns a copyNoneConverting and normalizing: most code
s.downcase!YesReturns nil when nothing changedIn-place change on its own line
a.casecmp?(b)Nonil for a non-stringEquality ignoring case, Unicode-aware
a.casecmp(b)NoFolds A-Z onlySorting ignoring case
s.capitalizeNoLowercases the restNormalizing names that may be all caps
s.sub(/\A./, &:upcase)NoNoneFirst letter only, rest kept
s.gsub(/(?<!\S)\S/, &:upcase)NoSkips letters after a hyphenEvery word, spacing and inner capitals kept
s.downcase(:fold)NoNot meant for displayKeys for case-insensitive lookups

Frequently asked questions

What is the Ruby version of Python's lower() or JavaScript's toLowerCase()?

It is downcase: "Hello".downcase returns "hello". The uppercase version is upcase. Like Python and JavaScript, they return a new string and leave the original alone; only the bang forms downcase! and upcase! change the string in place.

Why does downcase! return nil?

Bang methods return nil when they made no change, so "hello".downcase! is nil because the string was already lowercase. That lets you write puts "changed" if s.downcase!, but it breaks name = s.downcase! and chains such as s.downcase!.strip, which raise NoMethodError: undefined method 'strip' for nil. Use downcase when you need the result.

How do I check if a string is all lowercase or all uppercase?

Compare it with its converted copy: s == s.downcase is true when there is nothing left to lowercase. Note that "123" == "123".downcase is also true, since a string with no letters has no case. To require letters, use a regex: s.match?(/\A[[:lower:]]+\z/) is true for "école" and false for "123".

How do I lowercase every string in an array or every key in a hash?

Map over them: %w[A B].map(&:downcase) returns ["a", "b"], and map!(&:downcase) changes the array in place. For hash keys use transform_keys: { "Name" => 1, "AGE" => 2 }.transform_keys(&:downcase) returns {"name" => 1, "age" => 2}.

Does capitalize change the rest of the string?

Yes. capitalize upcases the first character and lowercases everything else, so "McDonald".capitalize is "Mcdonald" and "Hello World".capitalize is "Hello world". To upcase only the first character, use s.sub(/\A./, &:upcase).

Is there a case-insensitive equals in Ruby?

Yes, a.casecmp?(b) returns true when the strings match ignoring case and handles accented letters and ß. For a regex, add the i flag: "Ruby on Rails".match?(/rails/i). For an array, use list.any? { |s| s.casecmp?(x) }, since include? is case-sensitive.

Run it yourself

Open any of these in the full Ruby editor to tweak, run and share.

Ruby playground