Ruby字数是多少?

更新于
2026-10-03 21:18:54
1阅读来源:SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计263个文字,预计阅读时间需要2分钟。

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

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) 它确实涉及正则表达式,但它是正确的解决方案:

"Hi there 334".scan(/[[:alpha:]]+/).count # => 2

本文共计263个文字,预计阅读时间需要2分钟。

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

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) 它确实涉及正则表达式,但它是正确的解决方案:

"Hi there 334".scan(/[[:alpha:]]+/).count # => 2