Topic: Incorrect iterator function

Hi, I'm using Rails 3.0.0 and ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]

I'm running the block of code below from a file that I created. I named the file iterator.rb 

def name_animals()   
animals = %w( ant bee cat dog elk ) # create an array   
animals.each {|animal| puts animal } # iterate over the contents 
end  

puts name_animals 

when I run iterator.rb, I get the following result: 

new-host-2:demo tony$ ruby iterator.rb 
ant
bee 
cat 
dog 
elk 
ant 
bee 
cat 
dog 
elk  

When I run the same code in irb, I get the expected result:   

new-host-2:demo tony$ irb
>> animals = %w( ant bee cat dog elk )
=> ["ant", "bee", "cat", "dog", "elk"]
>> animals.each {|animal| puts animal }
ant
bee
cat
dog
elk
=> ["ant", "bee", "cat", "dog", "elk"]
>> 

Is this indicative on an error on my part of a bug in the iterator. Any help would be appreciated...

Thanks!!

Last edited by TonyArmstrong (2010-09-15 21:54:40)

Re: Incorrect iterator function

It prints out animal list twice because you're calling puts twice: 1) in the method itself 2) when calling the method ... so if you want your name_animals method to print out the list then just call it without puts.

Re: Incorrect iterator function

andain wrote:

It prints out animal list twice because you're calling puts twice: 1) in the method itself 2) when calling the method ... so if you want your name_animals method to print out the list then just call it without puts.

*Facepalm*  Ugggghhhhh.

Thanks for the quick -- and ultra simple -- answer.  SMH.

I didn't even notice that. Of course, it would be the simplest thing that I overlooked....