I’m stepping through some Ruby code of a hangman app made with Sinatra. Specifically, I’m looking at the post "/check" do path/function below. The first two steps of the function are predictable, namely, it shows the final_word variable, and then the char_clicked variable, but then the debugger reveals this Hash.new
Hash.new {|hash,key| hash[key.to_s] if Symbol === key }
before moving on in the function. I don’t see why post "/check" is creating a new hash at this point. It’s not explicit in the code, and it’s not obvious to me why this would be happening behind the scenes. I included the correct_guess method below as well, which gets invoked in “
final_word = session[:word]
(rdb:3) n
hangman.rb:79
char_clicked = params[:char_clicked]
(rdb:3) n
/Users/mm/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/sinatra-1.3.3/lib/sinatra/base.rb:916
Hash.new {|hash,key| hash[key.to_s] if Symbol === key }
(rdb:3) n
hangman.rb:80
correct_guess = Game.correct_guess?(char_clicked, final_word)
check path
post "/check" do
debugger
final_word = session[:word]
char_clicked = params[:char_clicked]
correct_guess = Game.correct_guess?(char_clicked, final_word)
if correct_guess
session[:revealed_word] = Word.reveal(session[:revealed_word], char_clicked, final_word)
session[:chars_left] = Word.chars_left(session[:revealed_word])
else
session[:incorrect_guesses] += 1
end
win = Game.win?(session[:chars_left], session[:incorrect_guesses])
{:word => session[:revealed_word], :correct_guess => correct_guess, :incorrect_guesses => session[:incorrect_guesses], :win => win}.to_json
end
Game correct_guess method
def correct_guess?(char_clicked, final_word)
final_word.include?(char_clicked)
end
Sinatra is creating the
paramshash for ‘indifferent access’ (so the hash keys can be accessed by string or symbols interchangeably).Hash.newtakes a block to determine what value to return if the key doesn’t exist.Example:
When you try to access
params[:char_clicked]the hash block executes so the debugger dumps the full line containing the block (the hash isn’t actually being created at that point):->
When the block is on a separate line the it’s easier to see which part of the code is being executed (i.e. just the block):
->