简体   繁体   English

如何将数组值与哈希数组合?

[英]How do I combine array values with array of hashes?

I have an array of hashes: 我有一系列哈希:

[{:foo => 1, :bar => 2}, {:foo => 2, :bar => 4} ...]

And an array of integers: 和一个整数数组:

[3, 6]

I want combine the values from the integer array and the hashes to end up with something like: 我希望将整数数组和散列中的值组合起来,结果如下:

[{:foo => 1, :bar => 2, :baz => 3}, {:foo => 2, :bar => 4, :baz => 6}]

I am currently doing this: 我目前正在这样做:

myArrayOfHashes.each_with_index |myHash, index|
    myHash[:baz] = myArrayOfIntegers[index]
end

Is that the right approach? 这是正确的方法吗?

I was imagining a more functional approach where I iterate over both arrays simultaneously, like something using zip + map . 我想象一个更实用的方法,我同时迭代两个数组,就像使用zip + map东西。

Try: 尝试:

require 'pp'

ary_of_hashes = [{:foo => 1, :bar => 2}, {:foo => 2, :bar => 4}]
[3, 6].zip(ary_of_hashes).each do |i, h|
  h[:baz] = i
end

pp ary_of_hashes

Which results in: 结果如下:

[{:foo=>1, :bar=>2, :baz=>3}, {:foo=>2, :bar=>4, :baz=>6}]

zip is a good tool for this, but map won't really buy much, at least nothing that you can't do as easily with each in this case. zip是一个很好的工具,但map不会真的买了,至少什么是你无法忍受的话那么容易each在这种情况下。

Also, don't name variables using CamelCase like myArrayOfHashes , instead use snake_case, like ary_of_hashes . 另外,不要使用像myArrayOfHashes这样的CamelCase来命名变量,而是使用snake_case,比如ary_of_hashes We use CamelCase for class names. 我们使用CamelCase作为类名。 Technically we can used mixed case for variables, but by convention we don't do that. 从技术上讲,我们可以使用混合大小写的变量,但按照惯例,我们不会这样做。

And, it's possible to use each_with_index , but it results in awkward code, because it forces you to use an index into [3, 6] . 并且,可以使用each_with_index ,但它会导致代码笨拙,因为它会强制您使用索引[3, 6] Let zip join the respective elements of both arrays and you'll have everything you need to massage the hash. zip连接两个数组的相应元素,你将拥有按摩哈希所需的一切。

map is useful when you want to leave the original objects intact: 当您想要保持原始对象完好无损时, map非常有用:

a = [{:foo => 1, :bar => 2}, {:foo => 2, :bar => 4}]
b = [3,6]
a.zip(b).map { |h, i| h.merge(baz: i) }
# => [{:foo=>1, :bar=>2, :baz=>3}, {:foo=>2, :bar=>4, :baz=>6}]
a.inspect
# => [{:foo=>1, :bar=>2}, {:foo=>2, :bar=>4}]
array_of_hashes.each { |hash| hash.update baz: array_of_integers.shift }

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

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