728x90
Ruby์ map vs each
๐ง ๋ ๊ฐ์ ๊ฐ์ฅ ํฐ ์ฐจ์ด์
- ๋ ๊ฐ์ ๊ฐ์ฅ ํฐ ์ฐจ์ด์ ์ ์๋ก์ด ๋ฐฐ์ด ๋ฐํ ์ฌ๋ถ์ ๋๋ค.
- map์ ์๋ก์ด ๋ฐฐ์ด์ ๋ฐํํ๊ณ , each๋ ์๋ก์ด ๋ฐฐ์ด์ ๋ฐํํ์ง ์์ต๋๋ค.
- ๊ฐ๋จํ ์์ ๋ฅผ ํตํด ์ดํด๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค
1๏ธโฃ map
names = [ "Dan", "Stella", "Elly" ]
upcase_names = names.map { |name| name.upcase }
puts names // [ "Dan", "Stella", "Elly" ]
puts upcase_names // [ "DAN", "STELLA", "ELLY" ]
- map์ ์๋ก์ด ๋ฐฐ์ด์ ๋ฐํํ๊ธฐ ๋๋ฌธ์ ๋ณํ๋ ๊ฐ์ด ๋์ค๋๊ฑธ ํ์ธํ ์ ์์ต๋๋ค.
- ์ฆ, ์๋ ๋ฐฐ์ด์ ๋ณํํ์ง ์๋ ์ฅ์ ์ด ์์ต๋๋ค.
- ์๋ ๋ฐฐ์ด๋ ๊ฐ์ด ๋ณ๊ฒฝํ๊ณ ์ถ๋ค๋ฉด
map!
์ ์ฌ์ฉํ๋ฉด ๋ฉ๋๋ค.
names = [ "Dan", "Stella", "Elly"]
names.map! { |name| name.upcase }
puts names // [ "DAN", "STELLA", "ELLY" ]
2๏ธโฃ each
names = [ "Dan", "Stella", "Elly" ]
upcase_names = names.each { |name| name.upcase }
puts names // [ "Dan", "Stella", "Elly" ]
puts upcase_names // [ "Dan", "Stella", "Elly" ]
- each๋ ๋ฐํํ์ง ์๊ธฐ ๋๋ฌธ์ ๋์ด ๋์ผํ ๊ฐ์ด ๋์ค๋๊ฑธ ํ์ธํ ์ ์์ต๋๋ค.
3๏ธโฃ collect
- map๊ณผ ๋์ผํ ๊ธฐ๋ฅ์ ํ๋ collect๋ ์์ต๋๋ค.
names = [ "Dan", "Stella", "Elly" ]
upcase_names = names.collect { |name| name.upcase }
puts names // [ "Dan", "Stella", "Elly" ]
puts upcase_names // [ "DAN", "STELLA", "ELLY" ]
728x90
728x90