title: Ruby Code not in Any Method
body: <p>General Ruby question:
  In Ruby, I frequently see code that's inside a class, but not part of a method. For example:</p>
  
  <pre><code>class DooDad
     attr_accessor :foo
  end
  </code></pre>
  
  <p>or</p>
  
  <pre><code>class Teacher &lt; ActiveRecord::Base
     has_many :students
  end
  </code></pre>
  
  <p>I think <code>attr_accessor</code> and <code>has_many</code> are methods getting invoked with the <code>:foo</code> or <code>:students</code> arguments, respectively, is that right? If so, when do these kinds of statements get executed. I tried this:</p>
  
  <pre><code>class DooDad
    attr_accessor :foo
    puts "I happened!"
    @foo = 7
  end
  </code></pre>
  
  <p>It doesn't seem to run these a part of the <code>new</code> method:</p>
  
  <pre><code>dd = DooDad.new
  dd.foo
  </code></pre>
  
  <p>outputs nil, and never spits out any <code>puts</code> stuff</p>
  
  <p>How exactly does all that work?</p>