3 ms·
Kind of a odd example just to use map/reduce where each works just fine: result = Hash.new(0) Dir['test?.txt'].each do |file| File.read(file).spl
by strmpnk 15y ago
Kind of a odd example just to use map/reduce where each works just fine:
result = Hash.new(0)
Dir['test?.txt'].each do |file|
File.read(file).split(' ').each {|word|
result[word.downcase.tr('.,\'', '')] += 1}
end
If you really needed map/reduce here you'd probably want to write it this way:
Dir['test?.txt'].map do |file|
Hash.new(0).tap {|result|
File.read(file).split(' ').each {|word|
result[word.downcase.tr('.,\'', '')] += 1}}
end.reduce do |result, partial|
result.merge(partial) {|k, v1, v2| v1 + v2}
end
- wedesoft 15y agoInteresting. I didn't know that you could pass a block to merge.