How to convert a string to lower or upper case in Ruby

How do I take a string and convert it to lower or upper case in Ruby?

0

11 Answers

Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase:

"hello James!".downcase #=> "hello james!" 

Similarly, upcase capitalizes every letter and capitalize capitalizes the first letter of the string but lowercases the rest:

"hello James!".upcase #=> "HELLO JAMES!" "hello James!".capitalize #=> "Hello james!" "hello James!".titleize #=> "Hello James!" (Rails/ActiveSupport only) 

If you want to modify a string in place, you can add an exclamation point to any of those methods:

string = "hello James!" string.downcase! string #=> "hello james!" 

Refer to the documentation for String for more information.

4

You can find out all the methods available on a String by opening irb and running:

"MyString".methods.sort 

And for a list of the methods available for strings in particular:

"MyString".own_methods.sort 

I use this to find out new and interesting things about objects which I might not otherwise have known existed.

10

Like @endeR mentioned, if internationalization is a concern, the unicode_utils gem is more than adequate.

$ gem install unicode_utils $ irb > require 'unicode_utils' => true > UnicodeUtils.downcase("FEN BİLİMLERİ", :tr) => "fen bilimleri" 

String manipulations in Ruby 2.4 are now unicode-sensitive.

0

The ruby downcase method returns a string with its uppercase letters replaced by lowercase letters.

"string".downcase 

2

... and the uppercase is:

"Awesome String".upcase => "AWESOME STRING" 

The Rails Active Support gem provides upcase, downcase, swapcase,capitalize, etc. methods with internationalization support:

gem install activesupport irb -ractive_support/core_ext/string "STRING ÁÂÃÀÇÉÊÍÓÔÕÚ".mb_chars.downcase.to_s => "string áâãàçéêíóôõú" "string áâãàçéêíóôõú".mb_chars.upcase.to_s => "STRING ÁÂÃÀÇÉÊÍÓÔÕÚ" 

The .swapcase method transforms the uppercase latters in a string to lowercase and the lowercase letters to uppercase.

'TESTING'.swapcase #=> testing 'testing'.swapcase #=> TESTING 
1

You can find strings method like "strings".methods You can define string as upcase, downcase, titleize. For Example,

"hii".downcase "hii".titleize "hii".upcase 

Since Ruby 2.4 there is a built in full Unicode case mapping. Source: . See Ruby 2.4.0 documentation for details:

Won't work for every, but this just saved me a bunch of time. I just had the problem with a CSV returning "TRUE or "FALSE" so I just added VALUE.to_s.downcase == "true" which will return the boolean true if the value is "TRUE" and false if the value is "FALSE", but will still work for the boolean true and false.

In combination with try method, to support nil value:

'string'.try(:upcase) 'string'.try(:capitalize) 'string'.try(:titleize) 

You Might Also Like