Books / Ruby for Beginners / Chapter 25
Hash vs Array in Ruby
Comparison of hashes and arrays
Initialization
Array: arr = []
Hash: hh = {}
Iteration
Array:
arr.each do |element|
# ...
end
Hash:
hh.each do |key, value|
# ...
end
or
hh.each_key do |key|
# ...
end
Data representation
Array, sequential collection of elements:
Hash, data stored in an associative manner:
Access
Array, access by index (type Integer):
arr[0]
arr[1]
arr[2]
, etc.
Hash, access by key where the key is an object of any type (Symbol, String, Integer, etc):
hh[:whatever]
hh['cat']
hh[31337]
, etc.
Purpose
Array: represent elements in sequential order.
Hash: keeps data in an associative manner with the fast access by a key. Can be used to keep configuration settings, options, parameters.
Class
Arrays: represented by Array class.
Hashes: represented by Hash class.