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,130 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.