轨道挡块范围

时间:2013-01-30 00:41:59

标签: ruby-on-rails ruby

我想计算这个块中的条目。因为ruby块变量作用域,我不处理这个代码。有什么方法可以解决这个问题吗?

    arr_showcase.each do |entry|
          @entry = ContestEntry.find_by_id(entry)
          if @entry.view_in_showcase == true
            @entry.view_in_showcase = false
            @entry.save
            entry_added_showcase += 1 
          else
            @entry.view_in_showcase = true
            @entry.save
            entry_removed_showcase += 1 
          end
    end
    redirect_to :back, :notice => "#{entry_added_showcase} Desings added, #{entry_removed_showcase} Designs removed."

2 个答案:

答案 0 :(得分:1)

您在哪里宣布entry_added_showcaseentry_removed_showcase?你必须在街区外初始化它们。

entry_added_showcase = entry_removed_showcase = 0
arr_showcase.each do |entry|
      @entry = ContestEntry.find_by_id(entry)
      if @entry.view_in_showcase == true
        @entry.view_in_showcase = false
        @entry.save
        entry_added_showcase += 1 
      else
        @entry.view_in_showcase = true
        @entry.save
        entry_removed_showcase += 1 
      end
end
redirect_to :back, :notice => "#{entry_added_showcase} Desings added, #{entry_removed_showcase} Designs removed."

答案 1 :(得分:0)

您需要在块的范围之外定义变量,如下所示:

entry_added_showcase = 0
entry_removed_showcase = 0
arr_showcase.each do |entry|
      @entry = ContestEntry.find_by_id(entry)
      if @entry.view_in_showcase == true
        @entry.view_in_showcase = false
        @entry.save
        entry_added_showcase += 1 
      else
        @entry.view_in_showcase = true
        @entry.save
        entry_removed_showcase += 1 
      end
end
redirect_to :back, :notice => "#{entry_added_showcase} Desings added, #{entry_removed_showcase} Designs removed."