将零插入多维数组

时间:2014-03-14 18:41:23

标签: ruby-on-rails ruby

我有一个bing_stats表,其记录包含来自在线广告系列的各种每日统计信息,如下所示:

user_id: "5", date: "20140306", conversions: ["0", "0", "1", "0"], spend: ["2.83", "0.45", "33.74", "0.00"], clicks: ["2", "1", "10", "0"], campaign_name: ["Seattle", "LA", "Houston", "DC"]>

用户在拉取记录的视图中输入日期范围。用户可能会暂时通过Bing暂停一些广告系列,这会使他们的日常记录看起来像这样:

user_id: "5", date: "20140306", conversions: ["0"], spend: ["2.83"], clicks: ["2"], campaign_name: ["Seattle"]>

当我尝试对日期范围内的所有记录进行求和时,它会导致问题

click_arrays = bing_records.map {|record| record.clicks}
@combined_clicks = click_arrays.map{|i| i.map{|s| s.to_i}}.transpose.map(&:sum)

=>Element size differs (1 should be 4)

为了解决这个问题,我试图首先确定给定集合中最大数组的长度。然后插入零代替缺少的元素。

click_arrays = bing_records.map {|record| record.clicks}
=> [["2", "1", "10", "0"], ["0", "2", "7", "0"], ["0", "1", "4", "0"], ["8"], ["1", "2", "12", "0"], ["1", "2", "14", "1"], ["1", "6", "11", "0"]]

click_arrays.min.count
=> 4

length = click_arrays.min.count
click_arrays.map {|n| n.in_groups_of(length, 0) {|g| p g}}

在irb控制台中执行此操作时,我得到了我想要的内容

=> ["2", "1", "10", "0"]["0", "2", "7", "0"]["0", "1", "4", "0"]["8", 0, 0, 0]["1", "2", "12", "0"]["1", "2", "14", "1"]["1", "6", "11", "0"]

但是在rails应用程序中,我得到一个未定义的方法`map'为nil:NilClass

=> [nil, nil, nil, nil, nil, nil, nil]

微量

NoMethodError - undefined method `map' for nil:NilClass:
app/controllers/adwordscampaign_controller.rb:56:in block in index
app/controllers/adwordscampaign_controller.rb:56:in index
(gem) actionpack-3.2.11/lib/action_controller/metal/implicit_render.rb:4:in send_action
(gem) actionpack-3.2.11/lib/abstract_controller/base.rb:167:in process_action
(gem) actionpack-3.2.11/lib/action_controller/metal/rendering.rb:10:in `process_action'
(gem) actionpack-3.2.11/lib/abstract_controller/callbacks.rb:18:in `block in process_action'
(gem) activesupport-3.2.11/lib/active_support/callbacks.rb:425:in       `_run__590333479__process_action__708665489__callbacks'
(gem) activesupport-3.2.11/lib/active_support/callbacks.rb:405:in `__run_callback'
(gem) activesupport-3.2.11/lib/active_support/callbacks.rb:385:in `_run_process_action_callbacks'
(gem) activesupport-3.2.11/lib/active_support/callbacks.rb:81:in `run_callbacks'
(gem) actionpack-3.2.11/lib/abstract_controller/callbacks.rb:17:in `process_action'

1 个答案:

答案 0 :(得分:0)

由于您没有指定您获取未定义方法错误的方法,我猜测方法是count。在这里我认为在Rails应用程序中发生了什么:

其中一条记录的nil属性值为clicks。这意味着click_arrays.min会返回nil。然后nil.count会给您错误。

因此,您不应使用#min来获取click_arrays中最长的元素。请注意,即使没有nil

的问题,它也会被破坏
[["1", "2"], ["3"]].min
=> ["1", "2"]`
[["3", "2"], ["1"]].min 
=> ["1"]

相反,我推荐这样的东西:

click_lengths = bing_records.map {|record| record.clicks.try(:count) || 0}
length = click_lengths.max

再往前走一点,我想你应该知道,如果残疾人队伍总是在名单的末尾,这只会给出正确的结果。在您的示例中,如果第二条记录显示["Seattle"]["Seattle", "LA", "Houston", "DC"],但不适用于["LA", "Houston"],则此功能可用。在这种情况下,数字不会正确排列。