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 Collections Ruby Hashes Ruby Hash Creation

SZE XU
SZE XU
1,053 Points

Hi I am new to Ruby & programming, so whats the difference between array and hash in Ruby?

Hi I am new to Ruby & programming, so whats the difference between array and hash in Ruby?

2 Answers

Martin Cornejo Saavedra
Martin Cornejo Saavedra
18,132 Points

An array can contain any object with an index. To obtain the object you must enter the index of the array. Example:

anyArray = ['house', 2, 'hello', 1200]
puts anyArray[2]   # hello

A hash can contain any object with a key asociated to it. To obtain the object you must enter the key of the array.

anyHash = {'name' => 'Martin', 'location' => 'Chile'}
puts anyHash['location']   # Chile

An array is an ordered list.

A Hash is an unordered list of key/value pairs, like a dictionary.