将来自两个不同数组的元素与Ruby中的Hash配对

Gen*_*nís 2 ruby arrays hash

假设我有这两个数组:

a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9, 10]
Run Code Online (Sandbox Code Playgroud)

我想要得到的是Hash如下:

c = { 1 => [1, 6], 2 => [2, 7], 3 => [3, 8], 4 => [4, 9], 5 => [5, 10] }
Run Code Online (Sandbox Code Playgroud)

到目前为止我遇到的唯一方法如下:

# Initialize the resulting Hash and fill in the keys.
c = {}
(a.length).times { |i| c[i + 1] = [] }

# Fill values
c.each_with_index do |(key), idx|
  c[key] = [a[idx], b[idx]]
end
Run Code Online (Sandbox Code Playgroud)

Ruby有更好或更好的方法吗?

提前致谢.

tok*_*and 10

功能方法:

Hash[a.zip(b).map.with_index(1) { |pair, idx| [idx, pair] }]
#=> {1=>[1, 6], 2=>[2, 7], 3=>[3, 8], 4=>[4, 9], 5=>[5, 10]}
Run Code Online (Sandbox Code Playgroud)

只是为了好玩,如果你想建立自己的抽象:前面的片段比它应该更详细,因为with_index,首先它只适用于枚举器(不是枚举),其次它将值作为第二个元素(它将是作为第一个更有用,这是大多数其他语言的作用).我们能做什么?添加我们自己的Enumerable#indexed方法,相反的方法.在这一点上我们也被迫添加Enumerable#to_h,所以最后我们能够编写这个纯粹的OOP,从左到右,声明性代码:

a.zip(b).indexed(1).to_h
Run Code Online (Sandbox Code Playgroud)

  • 我知道了.我错了.我弄明白了为什么.当使用`to_proc`并且该块接受多个块参数时,第一个变为接收器,其余变为参数. (2认同)

Chr*_*ich 8

c = Hash[(1..a.size).zip(a.zip(b))]
Run Code Online (Sandbox Code Playgroud)

这利用了Hash的键值对初始化器.