title: Ruby : Access array object by index vs iterator
body: <p>I'm pretty new to Ruby and the Rails framework.  My background is primarily Java.  Anyhow, I'm facing a weird situation.  I have a method in one of my models that returns associated models.  The association is as follows.  A has_many Bs, and B belongs to A (i.e. one-to-many)</p>
  
  <pre><code>class ModelA &lt; ActiveRecord::Base
    has_many :model_bs
  
    def get_bs
      ModelB.where(:a_id =&gt; id)
    end
  end 
  
  class ModelB &lt; ActiveRecord::Base
    belongs_to :model_a
  end
  </code></pre>
  
  <p>In my view, if I try to access the records (models) in the result set, I'm able to call its properties without any issue (Figure A).  Life is good.</p>
  
  <p>Figure A:</p>
  
  <pre><code>&lt;% bs = a.get_bs %&gt;
  &lt;% bs.each do |b| %&gt; 
    &lt;%= b.some_prop %&gt; 
  &lt;% end %&gt;
  </code></pre>
  
  <p>But if I try to access the models by index, I get an error saying that I can't call a method on a nil object (Figure B &amp; C).  </p>
  
  <p>Figure B:</p>
  
  <pre><code>&lt;% bs = a.get_bs %&gt;
  &lt;%= bs[0].some_prop) %&gt;
  </code></pre>
  
  <p>Or even..</p>
  
  <p>Figure C:</p>
  
  <pre><code>&lt;% bs = a.get_bs %&gt;
  &lt;%= bs[0].first %&gt;
  </code></pre>
  
  <p>Does not work.  I know it's user error (me).  I've looked at the documentation for accessing objects from a collection (in this case, I believe it's a Ruby array).  I've also searched here on StackOverflow.  I'm still left scratching my head.  I haven't quite found a similar thread.</p>