Created
March 16, 2012 20:46
-
-
Save mkoby/2052574 to your computer and use it in GitHub Desktop.
Intro to Ruby - 03 - Arrays & Hashes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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