how do i count each word in "wa ta're ba 100" such that (two words contracted like `ta're` are counted as one) and numbers are also counted as words? in ruby

To count each word in a given string in Ruby, you can use the following steps:

  1. Remove all punctuation marks except for apostrophes, as ta're should be counted as one word.
  2. Split the string into an array of words using whitespace as a delimiter.
  3. Count the number of elements in the resulting array.

Here's an example implementation:

main.rb
str = "wa ta're ba 100"

# Remove punctuation marks except for apostrophes
clean_str = str.gsub(/[^a-zA-Z0-9'\s]/, '')

# Split string into an array of words
words = clean_str.split

# Count the number of words
word_count = words.length

puts word_count
254 chars
13 lines

Running this code will output 4, as there are four words in the given string: wa, ta're, ba, and 100.

Please note that this implementation counts numbers as words as requested. If you want to exclude numbers from the word count, you can modify the regular expression used in the gsub method.

related categories

gistlibby LogSnag