【发布时间】:2014-02-05 22:03:40
【问题描述】:
我一直想弄清楚为什么wordscount返回的是字母而不是单词,但我不知道原因。
示例测试用例:
count_words("A man, a plan, a canal -- Panama")
# => {'a' => 3, 'man' => 1, 'canal' => 1, 'panama' => 1, 'plan' => 1}
count_words "Doo bee doo bee doo"
# => {'doo' => 3, 'bee' => 2}
代码如下:
class WordCount
def count_words(string)
changed = string.downcase.gsub(/[^a-zA-Z]/,"")
words = changed.split("")
counts = Hash.new(0)
words.each {|x| counts [x] += 1;}
return counts
end
end
test = WordCount.new
a = test.count_words("A man, a plan, a canal -- Panama")
b = test.count_words "Doo bee doo bee doo"
puts a
puts b
【问题讨论】:
-
WordCount#count_words返回一个将字符映射为整数的哈希值。有什么问题? -
只返回:
counts.keys.size -
它应该返回计算每个单词而不是字母,当我运行测试文件时,它会计算字母。
-
@user3221217 你需要用(word -> count)对返回
Hash吗?如果是,你已经这样做了 =) -
这些示例是期望的还是实际的行为?如果是想要的,那实际的又是什么呢?如果那是实际的,它们有何不同?
标签: ruby word-count