Skip to content

Instantly share code, notes, and snippets.

@alexanderjamesking
Created February 2, 2017 09:01
Show Gist options
  • Save alexanderjamesking/102a1760af64b5ab4a1e25b6199c913d to your computer and use it in GitHub Desktop.
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
# 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