开发者

NoMethodError In Ruby

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
开发者_StackOverflow中文版  @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


You're accessing two different instance variables:

  • The @on in post is an instance variable for your Sinatra instance.
  • The @on in createCal 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 the createCal method. Something like this:

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


Your instance variables probably aren't in the scope of the method. Try the following to test this theory:

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

And call it (in your /calendar block) with:

createCal(cal, @on, @off, @daycount)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜