title: Only execute code in erb if variable exists?
body: <p>Ruby newbie here who just started using Ruby with .erb templates and I'm having a problem with the code. I have a hangman game that's passing variables from the .rb file to the .erb file and everything was working fine until I tried to check it on initial load (no variables present) and it threw errors. So I figured I'd use <code>defined?</code> with an <code>if statement</code> to check if the variable exists and then execute the code if it does and ignore if doesn't. It works fine when I use:</p>
  
  <pre><code>&lt;% if defined?bad_guesses %&gt;
      &lt;%= bad_guesses %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>But the information I need is an array and when I try to use an .each or .times statement like this:</p>
  
  <pre><code>&lt;% if defined?bad_guesses %&gt;
    &lt;% bad_guesses.each do |i| %&gt;
      &lt;%= i %&gt;
    &lt;% end %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>I get:</p>
  
  <blockquote>
    <p>NoMethodError at /</p>
    
    <p>undefined method `each' for nil:NilClass</p>
    
    <p>C:/Projects/hangman/views/index.erb in block in singleton class</p>
    
    <ol start="18">
    <li><p>&lt;% bad_guesses.each do |i| %> hangman.rb in block in </p></li>
    <li><p>erb :index, :locals => {:game_status => game_status, :bad_guesses => bad_guesses, :good_guesses => good_guesses, :word => word}</p></li>
    </ol>
  </blockquote>
  
  <p>Any suggestions appreciated.</p>
  
  <p>Also, is this even the proper way to do this? When you make an .erb template that uses variables passed in from a class in your .rb file, how do you ignore it until it exists to the template?</p>
  
  <p>Passing variables using:</p>
  
  <pre><code>get '/' do
      if params['make'] != nil
          make = params['make'].to_i
          game_status, bad_guesses, good_guesses, word = Hangman.get_word(make)
      elsif params['guess'] != nil
          guess = params['guess'].to_s
          game_status, bad_guesses, good_guesses, word = Hangman.check_guess(guess)
      end
    erb :index, :locals =&gt; {:game_status =&gt; game_status, :bad_guesses =&gt; bad_guesses, :good_guesses =&gt; good_guesses, :word =&gt; word}
  end
  </code></pre>