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 Loops Ruby Loops The While Loop

Johnny Whitfield
Johnny Whitfield
14,024 Points

How is this code incorrect?

I don't understand why my loops aren't working. Please help.

loop.rb
def some_loop
  i=0
  while i < 5
    i += 1
  end
end

2 Answers

Robert Komaromi
Robert Komaromi
11,927 Points

The variable i is bound to the scope of the function. The i inside your function is separate from the i outside of it.

If you want to use your function in the code challenge, you can use it in the following way:

i = 0

def some_loop
    i = 0
    while i < 5
        i += 1
    end
    i
end

i = some_loop
Johnny Whitfield
Johnny Whitfield
14,024 Points

Thank you for explaining that for me, Robert! I really appreciate it. That worked.

Robert Komaromi
Robert Komaromi
11,927 Points

You're welcome! I'm glad you got it figured out :)