Created
February 2, 2017 09:01
-
-
Save alexanderjamesking/102a1760af64b5ab4a1e25b6199c913d to your computer and use it in GitHub Desktop.
Functional Ruby - using map to create a new array from an existing array
This file contains hidden or 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
# Looping through an array to form a new array | |
# non functional (imperative) way | |
my_array = [1,2,3,4,5] | |
new_array = [] # requires us to create a structure then modify it using push | |
my_array.each { | element | | |
new_array.push("number " + element.to_s) | |
} | |
puts "New array:" | |
puts new_array | |
puts "My array remains unchanged:" | |
puts my_array | |
# a more functional way to approach the problem, we don't need to declare the | |
# sequence beforehand and we don't need array.push as map creates a new array for us | |
my_array = [1,2,3,4,5] | |
new_array = my_array.map { | element | | |
"number " + element.to_s | |
} | |
puts "New array:" | |
puts new_array | |
puts "My array remains unchanged:" | |
puts my_array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment