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 Booleans Build a Simple Todo List Program Finding Array Items

James Copeland
James Copeland
12,550 Points

Finding Array Items help

What are the issues with my code? I can't seem to figure this one out. I've watched the preceding video several times now and don't see where I went wrong.

def find_index(name)
    index = 0
    found = false
    todo_items.each do |x|
      if x.name == name
        found = true
      end
      index += 1
      break if found
    end
    if found
      return index
    else
      return nil
    end
  end
James Copeland
James Copeland
12,550 Points

Now my code has disappeared and the code included with the challenge has changed completely (only included the specific method but now when revisiting, the whole class is included) - what is going on?

1 Answer

Seth Reece
Seth Reece
32,867 Points

Hi James,

It looks like you are breaking the loop out after you increment index, so if an item is found, your code will return the index of that item plus one. I got a pass with:

def find_index(name)
    index = 0
    found = false
    todo_items.each do |item|
      if item.name == name
        found = true
        break
      end
      index += 1
    end
    if found == true
      return index
    else
      return nil
    end
  end