2017-04-24 19 views
0

我试图把结果从我的投票模型在哈希进一步的用法,但我不知道如何从Ruby中的变量创建一个哈希键。见下面的例子:Rails模型结果哈希变量作为一个关键问题

def create_hash_array(campaign_votes) 
     target_hash = Hash.new 
     campaign_votes.each_with_index do |cv,i| 
      target_hash[cv.content_id] = {} if i == 0 

      if target_hash[cv.content_id].member?(cv.vote_button_id) 
      target_hash[cv.content_id][cv.vote_button_id] = (target_hash[cv.content_id][cv.vote_button_id]).to_i + 1 
      else 
      target_hash[cv.content_id] = {cv.vote_button_id => nil} 
      end 

     end 
     target_hash 
    end 

通常我得到了一个错误:

undefined method `member?' for nil:NilClass

,但它来自无法识别target_hash[cv.content_id],我怎样才能使不被认可target_hash[cv.content_id]变量?

+0

错误很明显,因为'target_hash [cv.content_id]'试图从密钥'cv.content_id'获取哈希值,该密钥尚未设置,并且为零,并且您正在对其调用'member'。基本上,你是否想用'cv.vote_button_id'键嵌套你的散列,如果它存在的话? –

回答

3

我觉得你的代码可以归结为:

def create_hash_array(campaign_votes) 
    target_hash = Hash.new { |h,k| h[k] = Hash.new(0) } 

    campaign_votes.each do |cv| 
    target_hash[cv.content_id][cv.vote_button_id] += 1 
    end 

    target_hash 
end 

这里有多种问题,很多做的过程中得到所有纠缠不清。您只在0索引位置初始化target_hash结构的元素,但每个campaign_vote可能有不同的content_id值,这意味着您错过了这些元素。

这种方法创建一个自动生成散列,将填充计数器哈希键,即哈希值缺省为0。这意味着你可以随时浏览他们+= 1会因为默认的工作。

这种方法在Ruby中很常见,特别是Hash.new(0),这对于执行任意对象的简单计数器非常方便。