Ruby,如何从两个数组创建散列?

时间:2021-10-13 12:42:32

I'm fairly a beginner in Ruby and I'm trying to do the following: Let's say I have two arrays:

我是Ruby的初学者,我正在尝试做以下事情:假设我有两个数组:

array_1 = ["NY", "SF", "NL", "SY"]
array_2 = ["apple", "banana"]

I want to merge the arrays to a hash so each object in array_1 will be assigned with the objects in array_2

我想将数组合并到散列中,这样array_1中的每个对象都将被分配给array_2中的对象

Thanks in advance.

提前谢谢。

3 个解决方案

#1


6  

x = [:foo, :bar, :baz]
y = [1, 2, 3]
x.zip(y).to_h # => {:foo=>1, :bar=>2, :baz=>3}

#2


2  

You can use the zip method, like so:

您可以使用zip方法,如下所示:

Hash[array_2.zip(array_1)]

散列(array_2.zip(array_1)]

#3


2  

h = array_1.product([array_2]).to_h
  #=> {"NY"=>["apple", "banana"], "SF"=>["apple", "banana"],
  #    "NL"=>["apple", "banana"], "SY"=>["apple", "banana"]}

We were given Array#to_h in MRI v2.0. For earlier versions, use Kernel#Hash:

我们在MRI v2.0中得到#to_h阵列。对于早期版本,使用Kernel#Hash:

h = Hash[array_1.product([array_2])]

but beware:

但是请注意:

array_2[0] = "cat"
array_2
  #=> ["cat", "banana"] 
h #=> {"NY"=>["cat", "banana"], "SF"=>["cat", "banana"],
  #    "NL"=>["cat", "banana"], "SY"=>["cat", "banana"]}

You may instead want:

你可能想要:

h = array_1.each_with_object({}) { |str,h| h[str] = array_2.dup }
  #=> {"NY"=>["apple", "banana"], "SF"=>["apple", "banana"],
  #    "NL"=>["apple", "banana"], "SY"=>["apple", "banana"]}

array_2[0] = "cat"
h #=> {"NY"=>["apple", "banana"], "SF"=>["apple", "banana"],
  #    "NL"=>["apple", "banana"], "SY"=>["apple", "banana"]}

#1


6  

x = [:foo, :bar, :baz]
y = [1, 2, 3]
x.zip(y).to_h # => {:foo=>1, :bar=>2, :baz=>3}

#2


2  

You can use the zip method, like so:

您可以使用zip方法,如下所示:

Hash[array_2.zip(array_1)]

散列(array_2.zip(array_1)]

#3


2  

h = array_1.product([array_2]).to_h
  #=> {"NY"=>["apple", "banana"], "SF"=>["apple", "banana"],
  #    "NL"=>["apple", "banana"], "SY"=>["apple", "banana"]}

We were given Array#to_h in MRI v2.0. For earlier versions, use Kernel#Hash:

我们在MRI v2.0中得到#to_h阵列。对于早期版本,使用Kernel#Hash:

h = Hash[array_1.product([array_2])]

but beware:

但是请注意:

array_2[0] = "cat"
array_2
  #=> ["cat", "banana"] 
h #=> {"NY"=>["cat", "banana"], "SF"=>["cat", "banana"],
  #    "NL"=>["cat", "banana"], "SY"=>["cat", "banana"]}

You may instead want:

你可能想要:

h = array_1.each_with_object({}) { |str,h| h[str] = array_2.dup }
  #=> {"NY"=>["apple", "banana"], "SF"=>["apple", "banana"],
  #    "NL"=>["apple", "banana"], "SY"=>["apple", "banana"]}

array_2[0] = "cat"
h #=> {"NY"=>["apple", "banana"], "SF"=>["apple", "banana"],
  #    "NL"=>["apple", "banana"], "SY"=>["apple", "banana"]}