首页 > 移动平台 > 详细

Merge array and hash in ruby if key appears in array

时间:2018-12-04 10:55:02      阅读:166      评论:0      收藏:0      [点我收藏+]

I have two arrays one = [1,2,3,4,5,6,7] and two = [{1=>‘10‘},{3=>‘22‘},{7=>‘40‘}]

Two will have one.length hashes or less. 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?

I‘d do it using Enumerable#reduce and 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)
one.map{|e| h[e].to_i}
# => [10, 0, 22, 0, 0, 0, 40]


Merge array and hash in ruby if key appears in array

原文:https://www.cnblogs.com/ldxsuanfa/p/10062513.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!