简体   繁体   English

如果键出现在数组中,则合并数组并在ruby中进行哈希处理

[英]Merge array and hash in ruby if key appears in array

I have two arrays one = [1,2,3,4,5,6,7] and two = [{1=>'10'},{3=>'22'},{7=>'40'}] 我有两个数组, one = [1,2,3,4,5,6,7]two = [{1=>'10'},{3=>'22'},{7=>'40'}]

Two will have one.length hashes or less. 两个将具有一个one.length哈希值。 I want a new array of values from two if it's key appears in one, if not then use 0. The new array would be [10,0,22,0,0,0,40] What is the best way to do this? 我想要一个从两个值组成的新数组,如果它的键出现在一个数组中,如果不是,则使用0。新数组将是[10,0,22,0,0,0,40]这样做的最佳方法是什么?

I'd do it using Enumerable#reduce and Hash#values_at : 我会使用Enumerable#reduceHash#values_at做到这Hash#values_at

two.reduce({}, :merge).values_at(*one).map(&:to_i)
# => [10, 0, 22, 0, 0, 0, 40]
h = [{1 => '10'}, {3 => '22'}, {7 => '40'}].inject(:merge).to_h
one.map{|e| h[e].to_i}
# => [10, 0, 22, 0, 0, 0, 40]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM