Ruby:访问由两个属性分组的哈希数组,用于" take_while"迭代

时间:2017-10-01 09:19:01

标签: arrays ruby

我有这个哈希数组:

tasks = [{:id=>19, :position_id=>3, :value=>2.55, :from=>2017-09-04 18:00:00 +0300},
        {:id=>10, :position_id=>3, :value=>0.16, :from=>2017-09-04 06:00:00 +0300}]

和另一个:

 inventory = 
 {[3, 2017-09-04 18:00:00 +0300]=>
  [{:id=>19, :position_id=>3, :value=>2.55, :day_part=>2017-09-04 18:00:00 +0300},
   {:id=>18, :position_id=>3, :value=>2.55, :day_part=>2017-09-04 18:00:00 +0300}],
  [3, 2017-09-04 06:00:00 +0300]=>
  [{:id=>11, :position_id=>3, :value=>0.57, :day_part=>2017-09-04 06:00:00 +0300},
   {:id=>10, :position_id=>3, :value=>0.16, :day_part=>2017-09-04 06:00:00 +0300}]}

我想为每个分组take_whileinventory,其中包含以下内容:

results = tasks.map do |bt|
  inventory[bt[:position_id],bt[:from]].take_while do |inv|
#do something here

然而,这不起作用,因为我收到此错误:ArgumentError: wrong number of arguments (given 2, expected 1)并且它指向行inventory[bt[:position_id],bt[:from]].take_while do |inv|

预期结果是我可以take_while对分组inventory进行position_id,其中分组属性与from匹配tasks。{/ p>

我该如何解决这个问题?谢谢。

更新

这些是我的哈希数组:

tasks = [{id:19, position_id:3, value:2.55, from: DateTime.new(2017,9,4,18,0,0,'+03:00')},
         {id:10, position_id:3, value:0.16, from: DateTime.new(2017,9,4,6,0,0,'+03:00')}]

inventory = 
  {[3, DateTime.new(2017,9,4,18,0,0,'+03:00')]=>
   [{:id=>19, :position_id=>3, :value=>2.55, :day_part=>DateTime.new(2017,9,4,18,0,0,'+03:00')},
    {:id=>18, :position_id=>3, :value=>2.55, :day_part=>DateTime.new(2017,9,4,18,0,0,'+03:00')}],
   [3, DateTime.new(2017,9,4,6,0,0,'+03:00')]=>
   [{:id=>11, :position_id=>3, :value=>0.57, :day_part=>DateTime.new(2017,9,4,6,0,0,'+03:00')},
    {:id=>10, :position_id=>3, :value=>0.16, :day_part=>DateTime.new(2017,9,4,6,0,0,'+03:00')}]}

目前我正在做这样的事情:

results = tasks.map do |bt|
  key = bt[:position_id], bt[:from].to_s
  inventory[key].take_while do |inv|
  #do something here

我收到错误NoMethodError: undefined method "take_while" for nil:NilClass

如果我更改为像key = [3, "2017-09-04 18:00:00 +0300"]这样的硬编码值,它会按预期工作。

我很困惑,因为我确定我的key = bt[:position_id], bt[:from].to_s给了我类似于硬编码值的数组。

1 个答案:

答案 0 :(得分:0)

这里需要一对额外的方括号:

botbuilder-apiai

如果没有额外的括号,则2个值inventory[[bt[:position_id], bt[:from]]] bt[:position_id]将被视为哈希查找的2个独立参数:bt[:from]

或者,您可以使用临时变量来澄清:

[]

注意:在构建密钥时,您不应该使用inventory_key = bt[:position_id], bt[:from] inventory[inventory_key].take_while... 。如果to_s中的键是inventory,那么您需要查找相同的内容。