Ruby辛纳屈无法获得while循环功能正确 - Ruby Sinatra Unable to get while loop to function correctly

- 此内容更新于:2016-02-02
主题:

试图让这个根据条件显示不同的页面。当定位在while循环,erb:游戏将显示一个空白页,while循环的外面显示正常,但是一旦你进入一个值的形式,它会自动重置为0。我失踪吗?

原文:

Trying to get this to display different pages based on condition. When positioned inside of the while loop, erb :game only displays an empty page, it displays properly outside of the while loop, but once you enter in a value in the form, it automatically resets the number to 0. What am I missing here?

get "/" do 
      count = 5  
      number = params["number"].to_i 

        if number == 0 
         erb :index
        else
          letters = find(number)
          while count > 0 do 

            guess = params["guess"]
            if letters.include?guess
              correct = check_guess(guess, letters)
            else
              count -= 1
            end
            disp = display(letters, correct)  
            erb :game, :locals => {:letters => letters, :disp => disp}   
          end

       end
end
楼主:相反的,您还可以使用和摆脱变量将在这种情况下不需要。的问题,请参考答案发布的其他用户。

(原文:Instead of while count > 0 do , you can also use 5.times do and get rid of count variable as it will not be needed in that case. For erb issue, refer to the answer posted by other user.)

解决方案:
你写线内循环。它不会工作。实际上没有意义。视图将整个循环完成后提交。结果呈现视图时,当时的价值。你不能呈现多个视图操作!你必须计算最后渲染你的模板。
原文:

You're writing erb line inside loop. It won't work. Actually it doesn't make sense. View will only be presented after the whole loop is done. As a result when view is rendering, by that time, value of count is 0.

You cannot render multiple view in an action! You'll have to calculate and then finally render your template.

网友:那么我该怎么去呢?设置不同的行动?即“/”后做……结束?

(原文:so how would i go about that? set up a different action? ie post "/" do ... end?)