Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 将数组转换为hash-Ruby_Arrays_Ruby - Fatal编程技术网

Arrays 将数组转换为hash-Ruby

Arrays 将数组转换为hash-Ruby,arrays,ruby,Arrays,Ruby,我有下面的数组,我想把它转换成一个散列,其中键是年龄,值是人名。此外,我想确保同龄的人属于同一把钥匙 年龄=[['alpha',20],'beta',21],'charlie',23],'delta',20],'gamma',23]] 如何将上面的内容转换为如下所示的散列 例如{20=>['alpha','delta']}等 我已尝试了以下代码,但我遇到了超出这一点的问题: hash = Hash[ages.collect {|item| [item[1], item[0]]} ] pp散列

我有下面的数组,我想把它转换成一个散列,其中键是年龄,值是人名。此外,我想确保同龄的人属于同一把钥匙

年龄=[['alpha',20],'beta',21],'charlie',23],'delta',20],'gamma',23]] 如何将上面的内容转换为如下所示的散列

例如{20=>['alpha','delta']}等

我已尝试了以下代码,但我遇到了超出这一点的问题:

hash = Hash[ages.collect {|item| [item[1], item[0]]} ]
pp散列


谢谢。

您可以先创建散列,然后在各个年龄段之间循环,将相似年龄段的成员收集到数组中

hash = Hash.new{|h,k|h[k]=Array.new()}
ages.each do |age|
  hash[age.last]<<age.first
end
p hash #{20=>["alpha", "delta"], 21=>["beta"], 23=>["charlie", "gamma"]}

可能的解决方案之一是使用:

hash=ages.each_with_objectHash.new{h,k | h[k]=[]}do | obj,res| res[obj.last]{20=>[alpha,delta],21=>[beta],23=>[charlie,gamma]}
还有另一种方法:使用

如果h没有键x,则变为

h[x] = nil || []

使h[x]设置为等于空数组,然后h[x]&:秒?以前有rails标签吗?说实话,我不记得rails和ruby中有什么。正如我所说,这个答案也依赖于主动支持方法。group_by是ruby可枚举的而不是主动支持谢谢。。。就像我说的,我无法跟踪,但知道这一点很好。那么h[x]=[*h[x],str]呢:。我知道它会生成一堆废弃的阵列,看起来很有趣
ages.each_with_object({}) do |(str,x),h|
  (h[x] ||= []) << str
end
  #=> {20=>["alpha", "delta"], 21=>["beta"], 23=>["charlie", "gamma"]}
h[x] = h[x] || []
h[x] = nil || []
enum = ages.each_with_object({})
  #=> #<Enumerator: [["alpha", 20], ["beta", 21], ["charlie", 23],
  #     ["delta", 20], ["gamma", 23]]:each_with_object({})> 
(str,x),h = enum.next
  #=> [["alpha", 20], {}] 
str
  #=> "alpha" 
x #=> 20 
h #=> {} 
(h[x] ||= []) << str
  #=> ["alpha"] 

(str,x),h = enum.next
  #=> [["beta", 21], {20=>["alpha"]}]