2

使用 Sinatra,无论出于何种原因,如果数字 > 1000,结果不会输出到浏览器。它立即显示“猜测您的数字 10000 需要 0 次尝试”。例如。因此,虽然 if 语句通过不执行 until 循环来工作,但它不会向浏览器显示输出。希望我只是在做一些非常愚蠢的事情。

简单: “数字必须小于 1000。” # 这不会输出到浏览器...为什么!?

不工作...

额外的信用: 存储最后尝试的猜测的最简单方法是什么,以便 rand 只尝试新值并比较每个数字一次。例如,使 /lottery/10 不可能有超过 10 次猜测。

下面的代码

get '/lottery/:number' do
  i = 0
  guess = 0
  number = params[:number].to_i
  if number > 1000 then
    "Number must be under 1000." # This doesn't output to browser... WHY!?
  else
    until number == guess do
      guess = rand(number) + 1
      puts "Guess: #{guess} | Attempt: #{i}"
      i +=1
    end
  end
  "It took #{i} tries to guess your number #{number}."
end
4

1 回答 1

4

基本思想是将您的方法返回的内容提供给浏览器(这是超级简化的,还有其他方法可以将内容返回)。在 ruby​​ 中,一个方法返回其最后一条语句的结果(除非事先发出对 return 的调用)。

现在,您get '/lottery/:number' do只返回最后一行的内容。您可以“手动”返回,也可以积累要返回的内容。

get '/lottery/:number' do
  i = 0
  guess = 0
  number = params[:number].to_i
  if number > 1000 then
    # Return "by hand" (stuff below does not execute).
    return "Number must be under 1000."
  else
    until number == guess do
      guess = rand(number) + 1
      puts "Guess: #{guess} | Attempt: #{i}"
      i +=1
    end
  end
  "It took #{i} tries to guess your number #{number}"
end

或者

get '/lottery/:number' do
  i = 0
  guess = 0
  content_to_send_back = ""
  number = params[:number].to_i
  if number > 1000 then
    # Will return that later:
    content_to_send_back = "Number must be under 1000."
  else
    until number == guess do
      guess = rand(number) + 1
      puts "Guess: #{guess} | Attempt: #{i}"
      content_to_send_back += "..#{i}"
      i +=1
    end
    content_to_send_back = "It took #{i} tries to guess your number #{number}"
  end
  # Ruby 'magic': actually it does 'return content_to_send_back':
  content_to_send_back
end

(请注意,该get块不是并且看起来不像您的典型方法,但我们可以将其视为。)

于 2013-11-02T13:21:48.887 回答