Ruby 中的无方法错误
我有一些 ruby 代码:
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
I have a bit of ruby code:
def createCal(cal)
mod = @on + @off #line creating error.
@daycount = 0
cal
end
This generates the following error: NoMethodError at /calendar undefined method `+' for nil:NilClass file: main.rb location: createCal line: 83
I am using this in Sinatra, and so I can print out @on and @off onto a webpage and I can confirm that they are in fact being loaded with values. I also do a '@ooo = @on + @off' in my haml template and that produces 7, which is to be expected because on is 4 and off 3.
Any ideas?
UPDATE:
Here's how I'm handling @on and @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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在访问两个不同的实例变量:
post
中的@on
是您的 Sinatra 实例的实例变量。createCal
中的@on
是来自您的 Doer 实例的实例变量。要根据需要使用
@on
和@off
,您需要将它们更改为传递给createCal
方法的参数。像这样的东西:You're accessing two different instance variables:
@on
inpost
is an instance variable for your Sinatra instance.@on
increateCal
is an instance variable from your Doer instance.To use
@on
and@off
like you want, you'll need to change them into arguments passed to thecreateCal
method. Something like this:您的实例变量可能不在该方法的范围内。尝试以下方法来测试这个理论:
并用以下方式调用它(在您的 /calendar 块中):
Your instance variables probably aren't in the scope of the method. Try the following to test this theory:
And call it (in your /calendar block) with: