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 1

Devin Scheu
Devin Scheu
66,191 Points

Ruby Boolean Help

Question: In the TodoList class, fill in the empty? method to return a boolean value. The empty? method should return true if there are no elements in the @todo_items array. The method should return false if there is more than one element in the @todo_items array.

My Code:

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 empty?
    if todo_items = []
      true
    else
      false
    end
  end

end

3 Answers

Stone Preston
Stone Preston
42,016 Points

you are comparing the todo_items array to the empty array to see if they are equal, so you need to use ==, not the assignment operator =

def empty?
  if todo_items == []
    true
  else
    false
  end
end

However, an more rubyist way to do this is to use the Array empty? method

def empty?
  return todo_items.empty?
end

since ruby uses an implicit return (the last line that executes is returned regardless of if the return keyword is used) you can even omit the return keyword giving the you very compact function below

def empty?
  todo_items.empty?
end
Devin Scheu
Devin Scheu
66,191 Points

Thanks again Stone, I forgot about the ? syntax

Great answer, thank you very much.

Thanks for the help, i tried everything else except the most simplest solution.

My answer was:

def empty?
  if @todo_items != []
    empty = false
  else
    empty ||= true
  end
end

After seeing Stone's answer, I wish I had thought of that. So simple! :D