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)
The most elegant solution I've seen on finding word count in Ruby was:
For most convenience, monkey patch String:
The main problem I see with your code is that you're coding, but you aren't coding in Ruby(style). You'll rarely see people use for/in here, for example. If you know how to write idiomatic Ruby, code that would take 10 lines in other languages are barely 1 line long here.