【问题标题】:NoMethodError at / undefined method `include?' for nil:NilClassNoMethodError at / undefined method `include?'对于零:NilClass
【发布时间】:2013-08-20 05:30:54
【问题描述】:

我正在尝试构建一个 sinatra ruby​​ 应用程序。我遇到了未定义的方法错误。我一直在尝试使用 method_missing 但我担心我一直在搞乱语法。我可以写一个 if else 语句来指定如果@x 返回 nil 怎么办?我有点新,可以使用一些帮助。谢谢!

我的 rb 文件

        get '/' do
  @x = params[:Body]
  session[:a] = (params[:Body].partition(' ').last.to_f / 2.2) * 0.58 if @x.include?("weight")
  session[:b] = params[:Body].partition(' ').last.to_f * 0.9672 if @x.include?("drinks")
  session[:c] = params[:Body].partition(' ').last.to_f * 0.015 if @x.include?("time")
  session[:d] = params[:Body].partition(' ').last if @x.include?("tweet")
  bac = round_to_precision(session[:b]/session[:a]-session[:c],3)
  timeleft = 40*(bac-0.08)/0.01
  hoursleft = (timeleft / 60).floor
  minutesleft = (timeleft - (hoursleft.floor * 60)).floor

  subliml = Twilio::TwiML::Response.new do |r|
    if bac >= 0.08
      r.Sms "Your BAC of #{bac} is over the federal limit of 0.08.  It will be #{hoursleft} hours and #{minutesleft} minutes until you are under the limit. Text tweet to anonymously exclaim your inebriation!"
    elsif bac.between?(0,0.08)
      r.Sms "Your BAC of #{bac} is under the limit"
    elsif bac.between?(-0.5,0)
      r.Sms "Have another beer"
    end
  end

  twiml = Twilio::TwiML::Response.new do |r|
      r.Sms "Hey there! Welcome to the BAC app! Please text weight followed by well your weight"
    end
  himl = Twilio::TwiML::Response.new do |r|
    r.Sms "Cool, now text drinks followed by how many drinks you've had"
    end
  timl = Twilio::TwiML::Response.new do |r|
    r.Sms "Almost there!!! Text time followed by how long have you been drinking"
    end
  swiml = Twilio::TwiML::Response.new do |r|
      r.Sms "Hmm, try something else"
    end
    if @x.include?("drunk") then
      twiml.text
    elsif @x.include?("weight")
      himl.text
    elsif @x.include?("drinks")
      timl.text
    elsif @x.include?("time")
      subliml.text 
    elsif @x.include?("tweet")
      request.set_form_data(
        "status" => session[:d])
      request.oauth! http, consumer_key, access_token
      http.start
      response = http.request request
    end
end

【问题讨论】:

    标签: ruby sinatra


    【解决方案1】:

    您似乎只是在@x 上调用include?。所以在某些情况下,它显然必须为零。如果它总是这样做,那么你只是得到了错误的参数。

    你可以检查一下:

    if @x.nil?
      # do something smart, maybe redirect to a different page
    end
    

    【讨论】:

      猜你喜欢
      • 2012-02-01
      • 2015-03-19
      • 2016-08-13
      • 2014-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      相关资源
      最近更新 更多