Ruby Build an Address Book in Ruby Search Appending Contacts

Patrick Shushereba
Patrick Shushereba
10,418 Points

Appending the contact variable

I'm having trouble with the second part of this challenge. I think I'm misunderstanding the directions. What I have is:

address_book.rb
contact = Contact.new
contact.first_name = "My"
contact.last_name = "Name"

address_book = AddressBook.new

address_book.push(contacts[contact])

But that's not running. So I need another way to approach this.

2 Answers

Jason Anders
MOD
Jason Anders
Treehouse Moderator 143,823 Points

Hey Patrick,

You're on the right track. You just are accessing the array and the variable in the wrong way.

Here is the corrected code, which shows how to access the array and append the variable.

contact = Contact.new
contact.first_name = "My"
contact.last_name = "Name"

address_book = AddressBook.new

address_book.contacts.push(contact)

You use .contacts to get into the array, then push the contact.

Hope this makes sense. Keep Coding! :)

Patrick Shushereba
Patrick Shushereba
10,418 Points

Just so I have this straight: I use .contacts because even though I don't see it, contacts is already a part of the AddressBook class. So when I create a new address_book object, using .contacts is the only way to access it? Sorry, if my way of writing this out isn't clear. I'm trying to understand. I'd also like to know why what I had didn't work. I just want to make sure I completely understand what's happening. If there's a previous video that explains it, point me to it and I'll review it. Thank you for your help.

Jason Anders
Jason Anders
Treehouse Moderator 143,823 Points

Hey Patrick. Sometimes the challenges are a bit vague, but other times they are referring to code that was done in the videos. If you watch this video at about 50 seconds in, the contacts array is created in the AddressBook Class, so that's where that comes from.

As for using address_book.contacts.push, Ruby uses dot notation to access the Array. So, in this example, you are telling ruby that there is a variable called address_book and inside there is an array named contacts and in that add this item.

It's been a while since I've done Ruby, but I hope this helps. :)

Patrick Shushereba
Patrick Shushereba
10,418 Points

So, it's like using any other method to access the array, like array.each etc? There's just an extra step because the array is contained within that variable, which in this case is an instance of a class? Thank you for your help, I think I have a better understanding.