LoginSignup
0
0

More than 5 years have passed since last update.

Refactoring used of map in Ruby

Last updated at Posted at 2019-03-05

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.

each
[1, 2, 3, 4, 5].each do |e|
  puts e
end
output
1
2
3
4
5

This is the most pupuler way of writing which use map.

map
[1, 2, 3, 4, 5].map{ |m| puts m }

map's output is same as each.

output
1
2
3
4
5

Refactoring used of map

This is bad smell, you should replace each with map.

each
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?

map
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.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0