Skip to content

Instantly share code, notes, and snippets.

@nbkhope
Created March 2, 2016 22:31
Show Gist options
  • Save nbkhope/57027169a5ff83485ebf to your computer and use it in GitHub Desktop.
Save nbkhope/57027169a5ff83485ebf to your computer and use it in GitHub Desktop.
# Example Code
# For blog entry about Ruby Arrays and Hashes
# Ruby Arrays #
# define an array with three elements
my_friends = ["James", "Ana", "David"]
# Displays the number of elements in the array (how many friends do I have?)
puts my_friends.length
puts my_friends[0] # the first friend, James
puts my_friends[1]
puts my_friends[2] # the last friend in the array -- David
###
my_friends = ["James", "Ana", "David"]
my_friends.push("Brian")
# check the contents of the array
p my_friends
my_friends.push("Landon")
my_friends.push("Cindy")
# check the contents of the array again
p my_friends
# removes the last item that was added to the array
my_friends.pop
# check the contents of the array
p my_friends
# removes the *first* item that was added to the array
my_friends.shift
# check the contents of the array
p my_friends
# replace the third element in the array with a new one
my_friends[2] = "Mark"
# check the contents of the array
p my_friends
# Ruby Hashes #
my_favorite_celebrity = {
"name" => "Anita Greatness",
"age" => 32,
"height" => 1.66
}
puts my_favorite_celebrity["name"]
puts my_favorite_celebrity["age"]
puts my_favorite_celebrity["height"]
###
# add a new key-value pair to the hash
my_favorite_celebrity["hometown"] = "San Francisco"
# conveniently check the contents of the hash
p my_favorite_celebrity
# replace an existing key-value pair with a new value
my_favorite_celebrity["name"] = "Anthony Greatdude"
# conveniently check the contents of the hash
p my_favorite_celebrity
###
# picking up from the previous code
p my_favorite_celebrity
my_favorite_celebrity.delete("age")
# check the contents of the hash
p my_favorite_celebrity
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment