Skip to content

Instantly share code, notes, and snippets.

@mkoby
Created March 16, 2012 20:46
Show Gist options
  • Select an option

  • Save mkoby/2052574 to your computer and use it in GitHub Desktop.

Select an option

Save mkoby/2052574 to your computer and use it in GitHub Desktop.
Intro to Ruby - 03 - Arrays & Hashes
# Basic Array
my_array = [1, 2, 3, 4, 5]
# Ruby arrays are zero-based arrays,
# meaning the first element is at index 0
my_array[1] # => 2
my_array[0] # => 1
# Except when you do negative indexes
my_array[-2] # => 4
# Adding items to an Array
my_array = [] # Creates an empty array
my_array << 2 # => [2]
my_array.push("A String") # => [2, "A String"]
# Removing an item
my_array.pop # => "A String"
my_array # => [2]
# Basic Hash
my_hash = { 'name' => "Michael Koby", 'age' => 32, 'websites' => ["http://www.codecasts.tv", "http://www.mkoby.com"] }
# Access by key
my_hash['age'] # => 32
# Using Ruby symbols for key names, Ruby 1.9 and above
my_hash = { :name => "Michael Koby", :age => 32, :websites => ["http://www.codecasts.tv", "http://www.mkoby.com"] }
# Access key by symbol
my_hash[:age] # => 32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment