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 trialDevin Scheu
66,191 PointsRuby 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:
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
42,016 Pointsyou 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
paul Bratslavsky
12,398 PointsThanks for the help, i tried everything else except the most simplest solution.
Samuel Stephen
8,493 PointsMy 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
Devin Scheu
66,191 PointsDevin Scheu
66,191 PointsThanks again Stone, I forgot about the ? syntax
tth2
9,347 Pointstth2
9,347 PointsGreat answer, thank you very much.