Skip to content

Instantly share code, notes, and snippets.

@jrosadocruz
Last active August 29, 2015 14:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrosadocruz/efeea6c7f1e02d75213e to your computer and use it in GitHub Desktop.
Save jrosadocruz/efeea6c7f1e02d75213e to your computer and use it in GitHub Desktop.
Ruby Hashes

Hash

A Hash is like a cabinet full of tagged folders. When you open the cabinet, you can choose the folder at a glance. A Hash stores data in key/value pairs. The new hash is the cabinet (just think about it as the name of the hash), the keys are the tagged folders, and the values are the sheets of paper inside the folder (think of the papers as Strings, Numbers, Arrays, etc).

Key

Hash keys, unlike like Arrays, can be: (1) strings, (2) numbers, (3) symbols and (4) arrays (though i don't see any use for this).

Unlike arrays, theres no need to know the order of the item. Therefore, a Hash is very useful for storing data (models) without any particular order.

Value

Hash values can be any ruby object. E.g: objects, methods, strings, numbers, floats, etc.

Creating hashes

There a are two ways to create a hash.

Long Syntax

You create an instance of the the Hash object using the .new method.

new_hash = Hash.new # Hash needs to be Capitalized, as you're creating an instance of the Hash object
new_hash["name"] = "Jose" # You assign a value to the hash key using the = 
new_hash["last_name"] = "Rosado"

Shorthand Syntax

You create an instance of the the Hash object using curly braces {}.

short_hash = {
    "name" => "Jose", # Always add a comma after the value
    :last => "Rosado", # You may use symbols as key. 
    last_name: "Rosado", # This is another way to use symbols as key.
    0 => "You can use numbers", # just like arrays.
    [1] => "This is number 1" # Heck!, you could even use an array... but don't do this
    # No need to add comma to after the last value
}

Retriving data from a hash

You retrieve data using brackets [], just like an Array, but using the key instead of a number.

puts new_hash["name"] # => "Jose"
puts new_hash["last_name"] # => "Rosado"
puts "#{new_hash['name']} #{new_hash['last_name']}" # => José Rosado
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment