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 Part 4: Removing Todo Items

Mateo Sossah
Mateo Sossah
6,598 Points

Why can't we use -> todo_items.delete(name)

I tried the following and it is not working. Anybody knows why and how it could be fixed?

def remove_item(name)
  todo_items.delete(name)
end

Thanks!

1 Answer

Mateo Sossah
Mateo Sossah
6,598 Points

I found an answer using both the for loop and todo_items.delete(name). I still would love an explanation as why my initial solution didn't work and if this one is valid as it looks shorter than the one in the video:

  def remove_item(name)
      for todo_item in todo_items do
        if todo_item.name == name
          todo_items.delete(todo_item)
        end
      end
  end

[MOD: added code blocks]

Kourosh Raeen
Kourosh Raeen
23,732 Points

Your initial solution doesn't work because todo_items is an array containing objects of type todo_item; however what you are trying to delete from todo_items is not an object of type todo_item, but an attribute/member variable of such object.

The second solution works since what you are deleting from the list_items array is a todo_item object.

I would also suggest adding a couple of return statements to the method:

def remove_item(name)
  for todo_item in todo_items do
    if todo_item.name == name
      todo_items.delete(todo_item)
      return true
    end
  end
  return false
end

You could also use the each method instead:

def remove_item(name)
  todo_items.each do |todo_item|
    if todo_item.name == name
      todo_items.delete(todo_item)
      return true
    end
  end
  return false
end

Hope this helps.