1. Introduction
Strings play a pivotal role in most programming tasks, and the ability to manipulate them is crucial. One common operation on strings is changing their case. In this guide, we will explore how to convert a string to uppercase and lowercase using Ruby.
2. Program Steps
1. Set up the Ruby development environment.
2. Prompt the user to input a string.
3. Convert the string to uppercase using the upcase method.
4. Convert the string to lowercase using the downcase method.
5. Display the converted strings to the user.
3. Code Program
# Prompt the user for a string
puts "Enter a string:"
input_string = gets.chomp
# Convert the string to uppercase
uppercase_string = input_string.upcase
# Convert the string to lowercase
lowercase_string = input_string.downcase
# Display the converted strings to the user
puts "Uppercase: #{uppercase_string}"
puts "Lowercase: #{lowercase_string}"
Output:
Enter a string: Hello World Uppercase: HELLO WORLD Lowercase: hello world
Explanation:
1. gets: Captures user input.
2. chomp: Removes the newline character from the user input.
3. upcase: This method converts all the alphabetic characters in a string to uppercase.
4. downcase: This method converts all the alphabetic characters in a string to lowercase.
By utilizing the built-in upcase and downcase methods of Ruby's String class, we can effortlessly change the case of a string.
Comments
Post a Comment