Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Ruby Blocks Working With Blocks Implementing Block Methods

Working with blocks - Challenge question

Jason returns array after the while loop here

  def each(&block)
    i = 0
    while i < array.length
      i += 1

We are asked to find the bug in the each method (array is missing) - but if I comment out array, the results are the same. Can someone explain why he needs to return array and why its considered a bug if its missing when the code still works without it?


not sure why the backticks aren't presenting the code properly here - sorry

1 Answer

The Core Ruby method #each (from Enumerable, which is mixed into the Array class) the returns the starting argument object, in this case 'array'. The code you provided (if you add array to the arguments) will iterate the block over every element in the array, but it will return 'nil'. Adding the 'array' line at the end of the method will ensure the method returns the array, which is the behavior expected from the #each method.