Skip to content

Instantly share code, notes, and snippets.

@nizaroni
Created June 18, 2015 21:40
Show Gist options
  • Save nizaroni/e4668d0f962ab2429b0c to your computer and use it in GitHub Desktop.
Save nizaroni/e4668d0f962ab2429b0c to your computer and use it in GitHub Desktop.
Brief explanation of hashes in Ruby.

Hashes in Ruby

A hash in Ruby is kind of like an array. For example, take an array of different ways to say "hello":

hellos = [ "hello", "hola", "bonjour" ]

We access individual values in the array by number:

hellos = [ "hello", "hola", "bonjour" ]
# Indexes:    0        1        2

puts hellos[0]  #=> "hello"
puts hellos[1]  #=> "hola"
puts hellos[2]  #=> "bonjour"

Rather than access these values by these numbers that have very little meaning, it would be great if we could access those values by a name. It turns out that hashes let us do that!

Here is that same information but in a hash:

hellos = {
  :english => "hello",
  :spanish => "hola",
  :french => "bonjour"
}

puts hellos[:english]  #=> "hello"
puts hellos[:spanish]  #=> "hola"
puts hellos[:french]   #=> "bonjour"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment