2

我有一些红宝石代码:

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

这会产生以下错误:NoMethodError at /calendar undefined method `+' for nil:NilClass file: main.rb location: createCal line: 83

我在 Sinatra 中使用它,因此我可以将 @on 和 @off 打印到网页上,并且我可以确认它们实际上正在加载值。我还在我的haml模板中做了一个'@ooo = @on + @off',它产生了7,这是可以预料的,因为on是4,off是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
4

2 回答 2

2

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

  • @oninpost是您的 Sinatra 实例的实例变量。
  • @onincreateCal是来自您的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
于 2011-09-06T20:47:04.850 回答
1

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

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

并使用以下命令调用它(在您的 /calendar 块中):

createCal(cal, @on, @off, @daycount)
于 2011-09-06T20:31:57.820 回答