|
|
|
|
|
by wedesoft
5477 days ago
|
|
And here's the equivalent Ruby program. In Ruby it is usually 'collect' and 'inject' instead of 'map' and 'reduce'. result = Dir.glob('test?.txt').collect do |file_name|
File.new(file_name, 'r').read.split(' ').collect do |word|
word.downcase.tr '.,\'', ''
end.inject Hash.new(0) do |hash,word|
hash[word] += 1
hash
end
end.inject do |all,hash|
(all.keys + hash.keys).uniq.inject Hash.new(0) do |acc,word|
acc[word] = all[word] + hash[word]
acc
end
end
p result
Edit: The Python example in the article is better because it merges hashes in the reduce step which facilitates parallelisation. |
|