# Problem iterating over and array of objects

**URL:** <https://www.ruby-forum.com/t/problem-iterating-over-and-array-of-objects/123566>\
**Category:** Rails\
**Created:** [December 18, 2007, 8:40pm UTC](https://www.ruby-forum.com/t/problem-iterating-over-and-array-of-objects/123566 "2007-12-18T20:40:57Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![spokra](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ba8739/32.png) [@spokra](https://www.ruby-forum.com/u/spokra)\
**Post date:** [December 18, 2007, 8:40pm UTC](https://www.ruby-forum.com/t/problem-iterating-over-and-array-of-objects/123566/1 "2007-12-18T20:40:57Z")

</div>

what am i missing here . the line a.each { |B| fails with the error

NoMethodError: You have a nil object when you didn’t expect it!  
You might have expected an instance of Array.  
The error occurred while evaluating nil.+  
from (irb):4:in `create\_menu’  
from (irb):17

but a is an array of menu objects… HELP!!!

def create\_menu(menu)  
a = Menu.find(:all, :conditions =\> “menu = '” + menu + “’”, :order  
=\> “‘order’” )  
if a.size then  
ret += “

\n”  
a.each { |b|  
ret += “- \n”  
ret += link\_to h(b.name), :action =\> b.controller  
+"/"+b.action, :id =\> b.name  
ret += “\n”  
ret += create\_menu(b.submenu)  
ret += “
\n”  
}  
ret += “
\n”  
end  
end

---

<div class="post-metadata">

**Author:** ![spokra](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ba8739/32.png) [@spokra](https://www.ruby-forum.com/u/spokra)\
**Post date:** [December 18, 2007, 10:14pm UTC](https://www.ruby-forum.com/t/problem-iterating-over-and-array-of-objects/123566/2 "2007-12-18T22:14:41Z")

</div>

On 18 Dec 2007, at 19:39, spokra wrote:

> what am i missing here . the line a.each { |B| fails with the error
> 
> NoMethodError: You have a nil object when you didn’t expect it!  
> You might have expected an instance of Array.  
> The error occurred while evaluating nil.+  
> from (irb):4:in `create\_menu’  
> from (irb):17

> 

a may be, but ret isn’t set to anything, and a quirk of ruby means  
that it will be nil.

In addition, using find like that leaves you open to sql injection  
problems and your if condition is bogus. Unlike some languages 0 is  
not synonymous with false

Fred
