将哈希推送到循环轨道中的数组中

时间:2011-05-25 11:06:19

标签: ruby-on-rails arrays ruby-on-rails-3 loops hash

我正在尝试在迭代每个循环的同时向数组添加哈希值。这是我的控制器代码:我正在努力解决的问题是在每个循环中设置@royaltiesbychannel变量:

def royalty(isbn)  
 sales_hash_by_channel = Sale.find_all_by_isbn_id(@isbn).group_by(&:channel_id)
 sales_hash_by_channel.each do |ch_id, sale_array|
  @royaltiesbychannel = Array.new() 
  value_total_by_channel = sale_array.sum(&:value) 
  quantity_total_by_channel = sale_array.sum(&:quantity)      
   @isbn.rules.each do |rule|
   next unless rule.channel_id == ch_id   
   case quantity_total_by_channel
   when 0..5000  
   @royaltiesbychannel = @royaltiesbychannel << {ch_id => value_total_by_channel * 0.5}
    # (some other case-when statements)             
  end
 end
end

在控制台中,当我将ch_id和值设置为new并将新值推送到数组中时:

@royaltiesbychannel = @royaltiesbychannel << {ch_id => value_total_by_channel * 0.5}

我得到了一系列漂亮的哈希:

[{1=>100000.0}, {2=>3000.0}] 

但是,当我在视图中执行@ royaltiesbychannel.inspect时,我只得到一个键值对:

[{2=>3000.0}]

对于参考:

@royaltiesbychannel.class = Array
@royaltiesbychannel.class = 1
@sales_hash_by_channel.class = Hash
@sales_hash_by_channel.size = 2
@isbn.rules.size = 4

所以看起来推入数组是覆盖而不是添加。我究竟做错了什么?我是否完全错过了循环和.push如何工作的观点?提前谢谢了。

3 个答案:

答案 0 :(得分:3)

您正在循环中初始化数组:
@royaltiesbychannel = Array.new()

每次重新初始化,因此您只得到一个结果。将它移到每个循环之外。

答案 1 :(得分:2)

您是否在@royaltiesbychannel的每次迭代期间将sales_hash_by_channel设置为新的Array对象,而不是在该循环之外将其初始化为一次?

答案 2 :(得分:1)

您的@royaltiesbychannel初始化位于第一个循环内部,因此每次再次启动该循环时,它会清空该数组。将它移到循环外面,你应该得到你想要的结果。

def royalty(isbn)
  @royaltiesbychannel = Array.new()
  sales_hash_by_channel = Sale.find_all_by_isbn_id(@isbn).group_by(&:channel_id)
  sales_hash_by_channel.each do |ch_id, sale_array|
    value_total_by_channel = sale_array.sum(&:value) 
    quantity_total_by_channel = sale_array.sum(&:quantity)      
    @isbn.rules.each do |rule|
      next unless rule.channel_id == ch_id   
      case quantity_total_by_channel
      when 0..5000  
        @royaltiesbychannel = @royaltiesbychannel << {ch_id => value_total_by_channel * 0.5}
        # (some other case-when statements)             
      end
    end
  end