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)
It does involve regular expressions but it's the correct solution:
"Hi there 334".scan(/[[:alpha:]]+/).count # => 2
Hm,
s = "Never eat shredded wheat"
puts s.split.count
# => 4
If you don't want to count underscores and digits:
s = "Never eat shredded wheat 1 _ ?"
puts s.split.reject { |w| w =~ /(\W|_|\d)/ }.count
# => 4
even more advanced regexp:
s = "Never __ 111 ?? eat shredded wheat. _Word?"
p s.split.reject { |w| w !~ /([a-zA-Z]+(_[a-zA-Z]+)*)/ }
# => ["Never", "eat", "shredded", "wheat.", "_Word?"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With