Home > OS >  How to map each value in an array to each value present in other array?
How to map each value in an array to each value present in other array?

Time:12-25

I'm pretty new to programming & Ruby. Any teachings on this one would be appreciated:

I have two arrays. The values in arrays are dynamic and can be changed based on what user inputs, e.g.:

name = [john, vick, nicki]
place = [usa, france]

I want to create a hash map with each value in the array: Name mapped to each value in array: Place

I'm expecting this output:

Hash = { "john" => "usa", "john" => "france", "vick => usa", "vick" => "france" "nicki" => "usa", "nicki" => "france" }

How can I achieve this?

CodePudding user response:

There are duplicated keys, such as john. A hash has unique keys and can have multiple values.

You could use an array in the hash, such as

result = { "john" => ["usa", "france"], "vick => ["usa", "france"] ... }

result = {}
name = ['john', 'vick', 'nicki']
place = ['usa', 'france']

name.each do |n|
  result[n] = place
end
puts result

CodePudding user response:

To map each value in one array to each value present in another array in Ruby, you can use the following method:

Create two arrays, for example:

names = ["john", "vick", "nicki"] places = ["usa", "france"] Use the Array#product method to combine the two arrays into a new array of all possible pairs:

pairs = names.product(places)

=> [["john", "usa"], ["john", "france"], ["vick", "usa"], ["vick", "france"], ["nicki", "usa"], ["nicki", "france"]]

Use the Enumerable#each_with_object method to iterate over the pairs array and add each pair to a new hash:

hash = pairs.each_with_object({}) do |(name, place), h| h[name] = place end

=> {"john"=>"usa", "vick"=>"usa", "nicki"=>"usa"}

This will create a new hash with the following values:

{"john"=>"usa", "vick"=>"usa", "nicki"=>"usa"} Note that in this example, the final value for each key in the hash will be the last value in the places array. If you want to map all possible pairs of values, you can use the Hash#merge method to add each pair to the hash, like this:

hash = pairs.each_with_object({}) do |(name, place), h| h.merge!(name => place) end

=> {"john"=>"france", "vick"=>"france", "nicki"=>"france"}

This will create a new hash with the following values:

{"john"=>"france", "vick"=>"france", "nicki"=>"france"}

  • Related