Ruby Program to Count Words in String
You can count words in a string in Ruby using
string.split.size, which splits the string by spaces and counts the resulting words.Examples
InputHello world
Output2
InputRuby is fun to learn
Output5
Input
Output0
How to Think About It
To count words in a string, first split the string into parts where spaces separate words. Then count how many parts you have. This works because each word is separated by spaces, so splitting by space gives all words as separate pieces.
Algorithm
1
Get the input string2
Split the string into words using spaces as separators3
Count the number of words obtained4
Return or print the countCode
ruby
puts "Enter a string:" input = gets.chomp word_count = input.split.size puts "Number of words: #{word_count}"
Output
Enter a string:
Hello Ruby world
Number of words: 3
Dry Run
Let's trace the input 'Hello Ruby world' through the code
1
Input string
input = 'Hello Ruby world'
2
Split string
input.split => ['Hello', 'Ruby', 'world']
3
Count words
word_count = 3
4
Print result
Output: 'Number of words: 3'
| Step | Value |
|---|---|
| Input string | Hello Ruby world |
| Split result | ['Hello', 'Ruby', 'world'] |
| Word count | 3 |
Why This Works
Step 1: Splitting the string
The split method breaks the string into an array of words using spaces as separators.
Step 2: Counting words
The size method counts how many elements (words) are in the array.
Step 3: Outputting the count
The program prints the number of words found in the string.
Alternative Approaches
Using scan with regex
ruby
puts "Enter a string:" input = gets.chomp word_count = input.scan(/\w+/).size puts "Number of words: #{word_count}"
This counts words by matching word characters, which can handle punctuation better but is slightly more complex.
Using count with split and reject
ruby
puts "Enter a string:" input = gets.chomp words = input.split.reject(&:empty?) word_count = words.size puts "Number of words: #{word_count}"
This method removes empty strings after splitting, useful if the string has multiple spaces.
Complexity: O(n) time, O(n) space
Time Complexity
Splitting the string scans each character once, so it takes linear time relative to the string length.
Space Complexity
The split method creates an array of words, which requires space proportional to the number of words.
Which Approach is Fastest?
Using split.size is fastest and simplest for most cases; regex scanning is more flexible but slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| split.size | O(n) | O(n) | Simple word counts with spaces |
| scan with regex | O(n) | O(n) | Counting words with punctuation |
| split + reject | O(n) | O(n) | Handling extra spaces cleanly |
Use
string.split.size for a quick and simple word count in Ruby.Beginners often forget to remove extra spaces, which can cause empty strings to be counted as words.