字数(红宝石)

jro*_*jro 3 ruby word-count

CoderByte提供了以下挑战:"使用Ruby语言,使用函数WordCount(str)获取传递的str字符串参数,并返回字符串包含的单词数量(即"Never eat shredded wheat"将返回4).将由单个空格分隔."

我解决了它,但有一个更简单的解决方案(不使用正则表达式或.length以外的方法)?我在for循环内部的for循环中有一个条件内部条件.我还在第一个for循环的内部和外部将当前变量设置为false.

这些糟糕的行为吗?有更好的解决方案吗?

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)
Run Code Online (Sandbox Code Playgroud)

Agi*_*gis 6

确实涉及正则表达式,但它是正确的解决方案:

"Hi there 334".scan(/[[:alpha:]]+/).count # => 2
Run Code Online (Sandbox Code Playgroud)