Ruby How to convert a string into upper and lower case?

This tutorial explains about how to convert a String into upper case or lower case

How to Convert a string into Lower case and uppercase in Ruby?

Ruby provides following methods

  • downcase

  • upcase

  • upcase: Convert the string into UPPER CASE

Below example, convert the string into upper case and assign the value to variable.

result="welcome".upcase
puts "#{result}"

Or Below example uses exclamation symbol(!) to the method that modifies the variable which is equal to convert the string int uppercase and assign the variable.

result="welcome"
result.upcase!
puts "#{result}"

The below program outputs the same result

WELCOME
  • downcase: Convert the string into lower or small case

Below example, convert the string into small case and assign the value to variable.

result="Welcome".downcase
puts "#{result}"

Or Below example uses exclamation symbol(!) to the method that modifies the variable which is equal to convert the string int lowercase and assign the variable.

result="Welcome"
result.downcase!
puts "#{result}"

The below program outputs the same result

welcome

There is another method swapcase that converts the UPPER CASE to lower case , and lower to upper case swapcase method that converts each character in a string to reverseable case. For example if letter is UPPERCASE, Convert to small case, If it is Small case, Convert to Upper case

result="welcome".swapcase
puts "#{result}"
result1="Welcome".swapcase
puts "#{result1}"
result2="WELCOME".swapcase
puts "#{result2}"

Output:

WELCOME
wELCOME
welcome