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 trialMichael Prince
23,132 PointsRuby Booleans Challenge 2
Why can't I use todo_items.include?(name) instead of iterating through the array?
Michael Prince
23,132 PointsMichael Prince 18,366 less than a minute ago Jonathan, my apologies. This is the first time I have asked a question in the forums here. I should have asked it from the challenge page but didn't. Here is the link: http://teamtreehouse.com/library/ruby-booleans/build-a-simple-todo-list-program/returning-boolean-values-part-2
The challenge is asking for you to fill out the contains? method it the array todo_items contains an item with the name argument. I was able to complete the challenge by iterating through the todo_items and checking for the name, but I'm not sure why I couldn't just call the include? method on the array.
Thanks for the help
1 Answer
Jonathan Johnson
Full Stack JavaScript Techdegree Student 952 PointsThat would work if you were just using strings, but notice on line 10, a new TodoItem
is constructed passing in the name
. So include?
doesn't really know how to check if two TodoItem
objects are the same (==
). By default, primitive types come with ways to check this, like strings.
To use include?
, a custom equality operator method needs to be defined on TodoItem
for your approach to work.
class TodoItem
attr_reader :name
def initialize(name)
@name = name
end
def ==(another_todo_item)
# This is where we define what it means
# to compare two `TodoItem`'s
@name == another_todo_item.name
end
end
[TodoItem.new('a'), TodoItem.new('b'), TodoItem.new('c')].include?(TodoItem.new('b'))
# => true
But that's a bit out of the scope of the challenge, but I hope it makes sense to you why your include?
solution didn't quite get there.
Michael Prince
23,132 PointsJonathan,
Thanks for the quick responses. Think I understand now.
Jonathan Johnson
Full Stack JavaScript Techdegree Student 952 PointsJonathan Johnson
Full Stack JavaScript Techdegree Student 952 PointsHi Michael!
Mind including a link to the challenge in question? Usually if you ask the question from within the challenge it will do that for you, but it seems not to have in this case.
Even better, an explanation of how you expect
include?
to work in this specific context would also help get you a complete answer.Thanks!