Refactoring used of map in Ruby
Overview
This is topic for practice in English, so Please don’t expect too much.
I used to write a each, when I just started ruby programming.
but I recently write map to refactor my source.
I write for that matter.
Version
ruby 2.3.1
comparison each with map
Let's comparison each with map.
This is the most pupuler way of writing which use each.
[1, 2, 3, 4, 5].each do |e|
puts e
end
1
2
3
4
5
This is the most pupuler way of writing which use map.
[1, 2, 3, 4, 5].map{ |m| puts m }
map's output is same as each.
1
2
3
4
5
Refactoring used of map
This is bad smell, you should replace each with map.
hoge = []
[1, 2, 3, 4, 5].each_with_index do |e, i|
hoge[i] = e * 100
end
This is code replaced with map.
It be elegant dosen't it?
hoge = [1, 2, 3, 4, 5].map{ |m| m * 100 }
I blieve if you use map, it will lead to be readable and reduce amount of your sorce.