Skip to content

Instantly share code, notes, and snippets.

@tibbon
Created September 24, 2014 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tibbon/753b54a94ed2222ac255 to your computer and use it in GitHub Desktop.
Save tibbon/753b54a94ed2222ac255 to your computer and use it in GitHub Desktop.
Ruby Array Map and Each
# .each is pretty easily, and simply loops through the array.
colors = ["red", "green", "blue"]
colors.each do |color|
puts color
end
# What is the "return value" of each?
mystery_colors = colors.each do |color|
puts color
end
# The mystery colors here are the original colors!!!
puts mystery_colors
# => ["red", "green", "blue"]
# the return value of .each is the original array!
# It would appear at first that .map does the same thing
colors.map do |color|
puts color
end
# But what is the return value of .map?
mystery_colors = colors.map do |color|
puts color
end
# But its all blank!
puts mystery_colors
# => [nil, nil, nil]
# Map returns a new array! The contents of each element are from the "return" of each do/end block iteration.
# (puts returns nil)
# This is useful for creating modified arrays
mystery_colors = colors.map do |color|
color.upcase
end
# Now you have upcased colors!
puts mystery_colors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment