简体   繁体   中英

How to map each value in an array to each value present in other array? [closed]

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, eg:

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

I want to create a hash map with each value in the name array mapped to each value in tge place array.

I'm expecting this output:

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

How can I achieve this?

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"}

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"]... }

Here's an easy example to fill create a given result hash (each element is equal to the place array):

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

# set up final hash, other options available.
result = {}

# loop to create the hash with names and arrays
name.each do |n|
  result[n] = place
end

# output the final hash
puts result

There's a predefined method to_h to cast to hash.

Used on name and place gives

name.collect {|i| [i, place]}.to_h
{"john"=>["usa", "france"], "vick"=>["usa", "france"], "nicki"=>["usa", "france"]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM