在Ruby中从两个数组中创建一个具有相同值的散列 [英] Creating a hash from two arrays with identical values in Ruby

查看:138
本文介绍了在Ruby中从两个数组中创建一个具有相同值的散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当两个数组中的值相同时,我在创建2个数组的散列时遇到了问题。
eg

  names = [test1,test2] 
numbers = [1 ,2]
Hash [names.zip(numbers)]

给我正是我需要的 => {test1=>1,test2=>2}



然而,如果 是相同的,那么它不能正常工作

  names = [test1,test1] 
数字= [1,2]
Hash [names.zip(numbers)]



<但是我预计结果是 {test1=>1 ,test1=>2}



任何帮助表示赞赏

解决方案

哈希不能有重复的键。永远。



如果他们被允许,你将如何访问2?如果你写 myhash [test1] ,你期望得到哪个值?相反,如果你期望

  names = [test1,test1,test2)在一个键下有几个值, ] 
numbers = [1,2,3]

Hash.new.tap {| h | names.zip(数字).each {| k,v | (h [k] || = [])<< v}}
#=> {test1=> [1,2],test2=> [3]}


I'm having issues creating a hash from 2 arrays when values are identical in one of the arrays. e.g.

names = ["test1", "test2"]
numbers = ["1", "2"]
Hash[names.zip(numbers)]

works perfectly it gives me exactly what I need => {"test1"=>"1", "test2"=>"2"}

However if the values in "names" are identical then it doesn't work correctly

names = ["test1", "test1"]
numbers = ["1", "2"]
Hash[names.zip(numbers)] 

shows {"test1"=>"2"} however I expect the result to be {"test1"=>"1", "test1"=>"2"}

Any help is appreciated

解决方案

Hashes can't have duplicate keys. Ever.

If they were permitted, how would you access "2"? If you write myhash["test1"], which value would you expect?

Rather, if you expect to have several values under one key, make a hash of arrays.

names = ["test1", "test1", "test2"]
numbers = ["1", "2", "3"]

Hash.new.tap { |h| names.zip(numbers).each { |k, v| (h[k] ||= []) << v } }
# => {"test1"=>["1", "2"], "test2"=>["3"]}

这篇关于在Ruby中从两个数组中创建一个具有相同值的散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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