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

Henry Miller
Henry Miller
7,945 Points

I don't understand what it wants me to do?

This is the challenge in finding array items and I don't get it. Please help? See my code below.

todo_list.rb
class TodoList
  attr_reader :name, :todo_items

  def initialize(name)
    @name = name
    @todo_items = []
  end

  def add_item(name)
    todo_items.push(TodoItem.new(name))
  end

  def find_index(name)
    index = 0
    found = false
    if found
      todo_items[index]
      return true
    else 
      return nil
    end

  end

end

2 Answers

Colin Bell
Colin Bell
29,679 Points
  1. You have to loop through each item first and check each item's name vs the name given.
  2. If the names match, set found equal to true and then break out of the each loop - no need to keep looking once you've already found it.
  3. If it is not found, add one to the index. Then it will start the loop over with the next todo_item until there aren't any items left to check.
  4. If the todo_item was found, return the index
  5. If after every todo_item in todo_items has been checked, and found wasn't true then return nil
  def find_index(name)

    index = 0
    found = false
    todo_items.each do |todo_item| #1
      if todo_item.name == name    #2
        found = true #2
      end
      if found #2
        break #2
      else
        index += 1 #3
      end
    end
    if found #4
      return index#4
    else
      return nil #5
    end

  end
Colin Bell
Colin Bell
29,679 Points

I'm sure it can be optimized, but I just pulled the code straight from the video and broke down what each portion was doing.

Something like this might cut down a few lines of code, though I didn't test it:

  def find_index(name)

    index = 0
    found = false
    todo_items.each do |todo_item| #1
      if todo_item.name == name    #2
        found = true #2
        break
      else
        index += 1 #3
      end
    end

    if found
      return index #4
    else
      return nil #5
    end
  end