CoderByte offers the following challenge: "Using the Ruby language, have the function WordCount(str) take the str string parameter being passed and return the number of words the string contains (ie. "Never eat shredded wheat" would return 4). Words will be separated by single spaces."
I solved it, but is there a simpler solution (that doesn't use regular expressions or methods other than .length)? I have a conditional inside of a conditional inside of a for-loop inside of a for-loop. I also set the current variable to false both inside and outside the first for-loop.
Are these poor practices? Is there a better solution?
def WordCount(string)
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
counter = 0
current = false
for i in 0...string.length
prev = current
current = false
for j in 0...alphabet.length
if string[i] == alphabet[j]
current = true
if prev == false
counter += 1
end
end
end
end
return counter
end
WordCount(STDIN.gets)
Hm,
If you don't want to count underscores and digits:
even more advanced regexp: