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 Returning Boolean Values: Part 2

yuva k
yuva k
4,410 Points

Find the value in the array results give me an error

  1. Please look at the line 14
  2. In the line 21, i dont understand why "todo_item.name == name" , why should we not mention only today_item, instead why are we using todo_item.name ?
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 contains?(name)
    todo_items.include?(name)
  end

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

1 Answer

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

In the line 21, i dont understand why "todo_item.name == name" , why should we not mention only today_item, instead why are we using todo_item.name ?

The TodoItem class looks like this:

class TodoItem
  attr_accessor :name
  def initialize(n)
    @name = n
  end
end

By default, a TodoItem object cannot be equal to a string; they have two different classes. So item == name would always be false. But item.name returns a string, and that can be equal to another string.

item = TodoItem.new("a")
puts item == "a" # false
puts item.name == "a" # true

Please look at the line 14

Your contains? method doesn't work for the same reason. include? goes through the TodoItem objects in todo_items, and tests whether current_item == name. That will always be false, so include? always returns false, so the challenge fails.

Instead, your contains? method should call find_index with the name that was passed to contains?. If find_index returns nil, then contains? should return false. If find_index returns a number, then contains? should return true. (Or, you can just take the return value of find_index and return that from contains?, since nil is treated as false in Ruby, and a number is treated as true.)