人生难得几回搏,此时不搏待何时。这篇文章主要讲述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‘}]
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?
【Merge array and hash in ruby if key appears in array】
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]
推荐阅读
- 映射器Mapping
- app|甘草医生医护版下载
- 在Godot中设计标题屏幕
- Godot的设计哲学
- 游戏节点设置
- Godot的第一个游戏项目示例
- 在Godot中编写场景脚本
- GDscript中的工具模式
- 故事书-故事对象(JSON)