NoMethodError在Ruby中

时间:2011-09-06 20:24:58

标签: ruby sinatra nomethoderror

我有一些红宝石代码:

def createCal(cal)
    mod = @on + @off #line creating error.
    @daycount = 0       
    cal
  end

这会产生以下错误:/ calendar的NoMethodError未定义的方法`+'代表nil:NilClass文件:main.rb位置:createCal行:83

我在Sinatra中使用它,因此我可以将@on和@off打印到网页上,我可以确认它们实际上已经加载了值。我也在我的haml模板中做了一个'@ooo = @on + @off'并产生了7,这是预期的,因为on是4而且是3。

有什么想法吗?

更新:

以下是我处理@on和@off

的方式
post '/calendar' do
  @on = params["on"]
  @off = params["off"]
  @date = params["date"]
  a = Doer.new
  @var = a.makeDate(@date)
  @on = @on.to_i
  @off = @off.to_i
  @ooo = @on + @off
  @cal = a.makeCal(@var)
  haml :feeling
end

2 个答案:

答案 0 :(得分:2)

您正在访问两个不同的实例变量:

  • @on中的post是Sinatra实例的实例变量。
  • @on中的createCal Doer 实例中的实例变量。

要使用您想要的@on@off,您需要将它们更改为传递给createCal方法的参数。像这样:

class Doer
  def createCal(cal, on, off)
    mod = on + off
    # more code...
    cal
  end
end

post '/calendar' do
  a = Doer.new
  date = a.makeDate params['date']
  @cal = a.makeCal date, params['on'], params['off']

  haml :some_template
end

答案 1 :(得分:1)

您的实例变量可能不在方法范围内。尝试以下方法来测试这个理论:

def createCal(cal, on, off, daycount)
  mod = on + off #line creating error.
  daycount = 0       
  cal
end

用(

)调用它(在您的/日历块中)
createCal(cal, @on, @off, @daycount)
相关问题