/ undefined方法`include?'中的NoMethodError为零:NilClass

时间:2013-08-19 21:21:06

标签: ruby sinatra

我正在尝试构建一个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

1 个答案:

答案 0 :(得分:0)

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

您可以查看:

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