Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 643
Heat Miser Avatar asked Jun 20 '09 00:06

Heat Miser


People also ask

How do I convert a string to lowercase in Ruby?

In Ruby, we use the downcase method to convert a string to lowercase. This method takes no parameters and returns the lowercase of the string that calls it. It returns the original string if no changes are made. Note: This method does not affect the original string.

How do you change a string into a upper case?

toUpperCase(ch2); String str1 = "The uppercase of the character '" + ch1 + "' is given as: " + ch3; String str2 = "The uppercase of the character '" + ch2 + "' is given as: " + ch4; // Print the values of ch1 and ch2..

What is Upcase in Ruby?

Symbol#upcase() : upcase() is a Symbol class method which returns the uppercase representation of the symbol object.


4 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.

like image 138
Sophie Alpert Avatar answered Oct 10 '22 10:10

Sophie Alpert


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.

like image 44
mlambie Avatar answered Oct 10 '22 09:10

mlambie


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.

like image 41
nurettin Avatar answered Oct 10 '22 11:10

nurettin


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

"string".downcase

https://ruby-doc.org/core-2.1.0/String.html#method-i-downcase

like image 22
Heat Miser Avatar answered Oct 10 '22 09:10

Heat Miser