session is nil initially

Skip to first unread message


Feb 10, 2020, 12:30:28 PM2/10/20
to sinatrarb
I have some basic code for a guess the number game (see below)

However, on the first post request after starting the server, I often get the error message that `session[:attempts]` is nil and the + method cannot be used:

NoMethodError at /guess

undefined method `+' for nil:NilClass

This error then goes away for all subsequent requests. I think the problem must be something to do with how Rack handles sessions, but can't think what it is. Anybody got any ideas?



Code below:

require 'sinatra'

enable :sessions
enable :inline_templates

get '/guess' do
  session[:number] = rand(1..100)
  session[:attempts] = 0
  @message = "I'm thinking of a number between 1 and 100, try and guess what it is. Attempts: #{session[:attempts]}"
  erb :guess

post '/guess' do
  number = session[:number]
  guess = params[:number].to_i
  session[:attempts] += 1
  redirect to('/success') if guess == number
  if guess < number then @message = "Too small, try again."
  elsif guess > number then @message = "Too big, try again."
  erb :guess

get '/success' do
  attempts = session[:attempts]
  "Well done, you guessed my number in #{attempts} attempt#{'s' if attempts > 1}!"


<!doctype html>
    <title>Guess the Number</title>

    <p><%= @message %></p>
    <form method="POST" action="/guess">
      <input name="number">
      <input type="submit" value="Guess">

Andrew Premdas

Feb 13, 2020, 6:15:49 AM2/13/20
If you restart the server and the first request is a post, then your new session hash won't have the attempts key so

session[:attempts] == nil

and your code in your post session[:attempts] +=1 is actually nil += 1

and nil += 1  gives undefined method + for nil error

You could try something like

session.key[:attempts] ? session[:attempts] +=1 : session[:attempts] = 1

which would  get you past your bug.

You received this message because you are subscribed to the Google Groups "sinatrarb" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To view this discussion on the web visit

Andrew Premdas


Feb 14, 2020, 5:39:10 AM2/14/20
to sinatrarb
Thanks Andrew - that makes sense, although I thought the first request was the get request after restarting the server, but maybe it was cached?

I like your idea anyway - makes it a bit more bulletproof!


To unsubscribe from this group and stop receiving emails from it, send an email to
Reply all
Reply to author
0 new messages