Ruby Program to Check Vowel or Consonant
Use
if 'aeiouAEIOU'.include?(char) to check if a character is a vowel; otherwise, it is a consonant in Ruby.Examples
Inputa
Outputa is a vowel
Inputz
Outputz is a consonant
InputE
OutputE is a vowel
How to Think About It
To check if a letter is a vowel or consonant, first get the character input. Then see if it is one of the vowels (a, e, i, o, u) ignoring case. If yes, say it is a vowel; if not, say it is a consonant.
Algorithm
1
Get a single character input from the user2
Convert the character to lowercase or check both cases3
Check if the character is in the set of vowels (a, e, i, o, u)4
If yes, print that it is a vowel5
Otherwise, print that it is a consonantCode
ruby
print 'Enter a character: ' char = gets.chomp if 'aeiouAEIOU'.include?(char) puts "#{char} is a vowel" else puts "#{char} is a consonant" end
Output
Enter a character: a
a is a vowel
Dry Run
Let's trace input 'a' through the code
1
Input character
User enters 'a'
2
Check vowel
'aeiouAEIOU'.include?('a') returns true
3
Print result
Print 'a is a vowel'
| Step | Character | Is Vowel? |
|---|---|---|
| 1 | a | true |
Why This Works
Step 1: Check membership
The include? method checks if the input character is inside the string of vowels.
Step 2: Case sensitivity
We include both uppercase and lowercase vowels to handle any case input.
Step 3: Output result
If the character is a vowel, print it as vowel; otherwise, print as consonant.
Alternative Approaches
Using a lowercase conversion
ruby
print 'Enter a character: ' char = gets.chomp.downcase if 'aeiou'.include?(char) puts "#{char} is a vowel" else puts "#{char} is a consonant" end
Converts input to lowercase first, so only lowercase vowels need to be checked.
Using a case statement
ruby
print 'Enter a character: ' char = gets.chomp case char.downcase when 'a', 'e', 'i', 'o', 'u' puts "#{char} is a vowel" else puts "#{char} is a consonant" end
Uses Ruby's case statement for clearer multiple condition checks.
Complexity: O(1) time, O(1) space
Time Complexity
Checking if a character is in a fixed string of vowels is a constant time operation.
Space Complexity
Only a few variables and a fixed string are used, so space is constant.
Which Approach is Fastest?
All approaches run in constant time; using include? or case is equally efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using include? with both cases | O(1) | O(1) | Simple and direct check |
| Using lowercase conversion | O(1) | O(1) | Cleaner code, fewer vowels to check |
| Using case statement | O(1) | O(1) | Clear multiple condition handling |
Always handle both uppercase and lowercase letters when checking vowels.
Forgetting to handle uppercase letters causes wrong results for capital vowels.