Ruby-将一个哈希的键转换为另一个哈希的值 [英] Ruby - keys of one hash into values of another hash

查看:135
本文介绍了Ruby-将一个哈希的键转换为另一个哈希的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须像这样散列:

hash1 = {
   "a" => 1,
   "b" => 1,
   "c" => 1,
   "d" => 1
}

hash2 = {
  "1" => 1,
  "2" => 1,
  "3" => 1,
  "4" => 1
}

我需要合并它们,所以我最终得到了这个结果:

And I need to merge them so I end up with this:

hash1 = {
  "a" => "1",
  "b" => "2",
  "c" => "3",
  "d" => "4"
}

但是我不知道从哪里开始.帮助表示赞赏.

But I don't know where to begin. Help appreciated.

推荐答案

您可以尝试以下操作:

Hash[hash1.keys.zip(hash2.keys)]

首先,您将使用hash1.keyshash2.keys获得每个哈希的键数组:

At first, you get array of keys for each hash with hash1.keys and hash2.keys:

["a", "b", "c", "d"]
["1", "2", "3", "4"]

第二,您使用hash1.keys.zip(hash2.keys)创建一个数组数组:

Secondly, you create an array of arrays with hash1.keys.zip(hash2.keys):

[["a", "1"], ["b", "2"], ["c", "3"], ["d", "4"]]

然后Hash[<...>]创建一个Hash,其中第一个内部数组的第一个值作为键,第二个作为值:

Then with Hash[<...>] you create a Hash where the first value from the first inner array goes as key and the second as value:

{"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4"}

示例

这篇关于Ruby-将一个哈希的键转换为另一个哈希的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆