Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.