Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word Count (Ruby)

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)
like image 833
anon Avatar asked Apr 02 '26 18:04

anon


2 Answers

It does involve regular expressions but it's the correct solution:

"Hi there 334".scan(/[[:alpha:]]+/).count # => 2
like image 58
Agis Avatar answered Apr 04 '26 06:04

Agis


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?"]
like image 24
Rustam A. Gasanov Avatar answered Apr 04 '26 06:04

Rustam A. Gasanov