1行のテキストのすべての単語を数えたい。私はこれを行うためにマップを使用しており、キーの単語と値の整数を使用しています。すべての値が整数になることをRubyに伝える方法がわかりません。イテレータのブロック内に醜い分岐を配置する必要があります。
# in the constructor
@individual_words = {}
def count_words_from( text_line )
text_line.each do |line|
line.scan(/\p{Word}+/)
.reject{ |string| string =~ /\d/ }
.each do |word|
if @individual_words[ word ] == nil then # This is ugly
@individual_words[ word ] = 1 # This is ugly as well
else
@individual_words[ word ] += 1
end
end
end
end
簡単に言うと、次のJava行のようなことをしたいと思います。
Map<String, Integer> individualWords;
単語の最初の出現のタイプをからに変更する必要をなくすNil
ためInteger
。