Skip to content

Instantly share code, notes, and snippets.

@samuraijane
Created April 17, 2015 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuraijane/9928aa0feb2cf47fe17d to your computer and use it in GitHub Desktop.
Save samuraijane/9928aa0feb2cf47fe17d to your computer and use it in GitHub Desktop.
Sometimes you need to create a new hash that blends two arrays, where the content in first array become the keys and the content in the second array become the values in the new hash. You can also assign that same value to each key if necessary.
# OPTION 1
# array_a is an array that holds what will become the keys in the new hash.
# array_b is an array that holds what will become the values in the new hash.
# Create a new empty hash.
my_hash = {}
# Send array_a and array_b into the new hash.
array_a.each_with_index { |key, value| my_hash[key] = array_b[value] }
# This works well for arrays that have the same amount of content so that things
# line up. I haven't researched what happens with one array has more content
# than the other.
# OPTION 2
# array_a is an array that holds what will become the keys in the new hash.
# array_b is an array that holds what will become the values in the new hash
# but unlike the example in Option 1, this value is actually another array and
# will be the same for each key
# Create a new empty hash.
my_hash = {}
# Send array_a and array_b into the new hash.
array_a.each_with_index { |key, value| my_hash[key] = array_b }
# Because I did not declare '[value]' after 'array_b', there is no iteration on
# array_b and the array itself becomes the value for each key.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment