Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Ruby Collections Ruby Arrays Accessing Items in Arrays

This seems like an easy challenge but not getting it.

Can someone help me here?

array.rb
grocery_list = ["milk", "eggs", "bread", "ice cream", "potatoes", "pie"]

grocery_list.first[0]

3 Answers

Seth Kroger
Seth Kroger
56,405 Points

To reference an item in an array we usually use the brackets after the array: array[position] We start counting the postition from zero, so the first item in the array is

grocery_list[0]

Ruby does have a .first methods for arrays and can be used like this:

grocery_list.first

But you don't use both together. Also the challenge says to put the item in a variable called first_item so don't forget to assign it.

first_item = grocery_list[0]

There are a few things here that are preventing you from reaching the correct answer:

  1. You need to create a variable called first_item.
  2. To access the first item in a standard array you use the arrays variable name followed by [0]. grocery_list[0] for example.
  3. Assign the first_item variable the first item in grocery_list like below.
first_item = grocery_list[0];

Thanks for your explanation. Very helpful.

Thanks for explaining this. Gives me much clarity.