Last active
July 9, 2020 23:15
-
-
Save Haumer/22478b9b1a884027dbd98d504d672fc7 to your computer and use it in GitHub Desktop.
Short showcase of .each, .map and .map! and what they return
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# .EACH, .MAP and .MAP! | |
numbers = [1, 2, 3, 4, 5] # this is our starting/original array | |
# EACH | |
numbers.each do |number| | |
number * 2 # simply multiplying each value by 2 | |
end | |
#=> [1, 2, 3, 4, 5] | |
p numbers | |
# the original array is unchanged! | |
# MAP | |
numbers.map do |number| | |
number * 2 # simply multiplying each value by 2 | |
end | |
#=> [2, 4, 6, 8, 10] | |
# the output is a copy of the original in its changed state! | |
p numbers | |
# However the original array is still unchanged! | |
#=> [1, 2, 3, 4, 5] | |
# MAP! | |
numbers.map! do |number| | |
number * 2 # simply multiplying each value by 2 | |
end | |
#=> [2, 4, 6, 8, 10] | |
p numbers | |
#=> [2, 4, 6, 8, 10] | |
# .map! is destructive so both the output and the original array are [2, 4, 6, 8, 10] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment