09/01/25 20:03:10
>>805
配列要素をeachで枚挙することを厭ってはいけない
特にRubyではね
words = ["apple", "orange", "lemon"]
sentence = ["apple is red","orange is not blue","lemon is yellow","apple is not orange","lemon is not red"]
counts = {"apple"=>0, "orange"=>0, "lemon"=>0}
sentence.each do |s|
words.each do |word|
if /#{word}/ =~ s then
counts[word] = counts[word]+1
end
end
end
p counts
結果:
{"orange"=>2, "apple"=>2, "lemon"=>2}