【发布时间】:2017-09-17 04:55:42
【问题描述】:
我有两个这样的哈希数组:
h1=[{id:1, item:1, from: DateTime.new(2017,9,4,6,0,0,'+0300'), to: DateTime.new(2017,9,4,17,59,59,'+0300'), value:10},
{id:1, item:2, from: DateTime.new(2017,9,4,18,0,0,'+0300'), to: DateTime.new(2017,9,4,23,59,59,'+0300'), value:10}]
h2=[{id:1, item:1, date: DateTime.new(2017,9,4,6,10,0,'+0300'), value:5},
{id:2, item:1, date: DateTime.new(2017,9,4,7,20,0,'+0300'), value:7},
{id:3, item:1, date: DateTime.new(2017,9,4,8,05,0,'+0300'), value:10},
{id:4, item:1, date: DateTime.new(2017,9,4,18,19,10,'+0300'), value:1},
{id:5, item:2, date: DateTime.new(2017,9,4,19,20,0,'+0300'), value:2},
{id:6, item:2, date: DateTime.new(2017,9,4,22,22,0,'+0300'), value:5},
{id:7, item:2, date: DateTime.new(2017,9,5,23,0,0,'+0300'), value:1}]
我需要在每个 h1 下嵌套来自 h2 的任何哈希值,这些哈希值符合条件:
-
item值(例如,两个哈希中的item:1) -
来自
h2的date在from-to范围内h1
到目前为止,我可以简单地将所有哈希嵌套在h1 下:
my_hash = h1.each do
|mh| mh[:inventory]=h2
end
我相信标准匹配的事情可以用这个来完成:
h2.find{ |i| i[:item] == h1[:item] && i[:date].between?(h2[:from], h2[:to]) }
请问,我应该如何将它组合在一起以使其正常工作?谢谢!
更新 2
我正在尝试为每个 h1 与 h2 匹配的哈希找到这个:
my_hash = h1.each do |hsh|
h2.each do |hsh2|
hash=hsh2.find{|h| h[:item] == hsh[:item] && h[:date].between?(hsh[:from],hsh[:to])} if hash
hsh[:inventory] = hash
end
end
但是我收到错误ArgumentError: wrong number of arguments (given 1, expected 0) from (pry):12:in "hash"。
请问我在这里做错了什么?
更新 3 如果可能的话,理想的输出应该是这样的:
=> [:order=>{:id=>1,
:item=>1,
:from=>Mon, 04 Sep 2017 06:00:00 +0300,
:to=>Mon, 04 Sep 2017 17:59:59 +0300,
:value=>10,
:inventory=>
{:id=>1, :item=>1, :date=>Mon, 04 Sep 2017 06:10:00 +0300, :value=>5},
{:id=>2, :item=>1, :date=>Mon, 04 Sep 2017 07:20:00 +0300, :value=>7},
{:id=>3, :item=>1, :date=>Mon, 04 Sep 2017 08:05:00 +0300, :value=>10}
:order=>{:id=>1,
:item=>2,
:from=>Mon, 04 Sep 2017 18:00:00 +0300,
:to=>Mon, 04 Sep 2017 23:59:59 +0300,
:value=>10,
:inventory=>
{:id=>4, :item=>2, :date=>Mon, 04 Sep 2017 18:19:10 +0300, :value=>1},
{:id=>5, :item=>2, :date=>Mon, 04 Sep 2017 19:20:00 +0300, :value=>2},
{:id=>6, :item=>2, :date=>Mon, 04 Sep 2017 22:22:00 +0300, :value=>5},
{:id=>7, :item=>2, :date=>Mon, 04 Sep 2017 23:00:00 +0300, :value=>1}}]
对于每个h1,我想提供新的密钥order,然后在inventory 密钥下嵌套适当的h2 哈希。
【问题讨论】:
-
你能添加一个预期的输出吗?
-
在两个输入哈希中都没有键
:inventory。 -
@SebastiánPalma 请参阅上面的更新 3,其中我添加了输出示例 + 扩展了我关于父和子哈希键的问题。
-
@mudasobwa 请参阅上面的更新 3,我通过输出示例清除了我的问题。