Ruby - Count Vowels in a String

1. Introduction

Counting vowels in a string is a common task in text processing, whether for linguistic analysis, algorithm challenges, or simply as a foundational string manipulation exercise. In this tutorial, we'll look at how to count the number of vowels in a given string using Ruby.

2. Program Steps

1. Set up the Ruby development environment.

2. Prompt the user to input a string.

3. Process the string to count the number of vowels (A, E, I, O, U, and their lowercase counterparts).

4. Display the number of vowels found in the string to the user.

3. Code Program

# Prompting the user for a string
puts "Enter a string:"
input_string = gets.chomp
# Counting the vowels in the string
vowel_count = input_string.downcase.scan(/[aeiou]/).count
# Displaying the number of vowels
puts "The number of vowels in '#{input_string}' is: #{vowel_count}"


Enter a string:
Hello, World!
The number of vowels in 'Hello, World!' is: 3


1. gets: This method captures user input. The input is read as a string.

2. chomp: Removes the newline character from the string, which is added when the user presses Enter.

3. downcase: Converts the entire string to lowercase. This ensures that both upper and lower case vowels are counted.

4. scan: This method searches the string for matches based on the provided regular expression.

5. /[aeiou]/: This is a regular expression that matches any single vowel character. It's used in conjunction with scan to find all vowel occurrences in the string.

6. count: This method returns the number of matches found by scan.

With these steps, we can easily count the number of vowels in any given string using Ruby.