-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Exercise 39: Hashes, Oh Lovely Hashes
- Loading branch information
1 parent
92c7a36
commit 387f4f8
Showing
1 changed file
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
# create a mapping of state to abbreviation | ||
states = { | ||
'Oregon' => 'OR', | ||
'Florida' => 'FL', | ||
'California' => 'CA', | ||
'New York' => 'NY', | ||
'Michigan' => 'MI' | ||
} | ||
|
||
# create a basic set of states and some cities in them | ||
cities = { | ||
'CA' => 'San Francisco', | ||
'MI' => 'Detroit', | ||
'FL' => 'Jacksonville' | ||
} | ||
|
||
# add some more cities | ||
cities['NY'] = 'New York' | ||
cities['OR'] = 'Portland' | ||
|
||
# puts out some cities | ||
puts '-' * 10 | ||
puts "NY State has: #{cities['NY']}" | ||
puts "OR State has: #{cities['OR']}" | ||
|
||
# puts some states | ||
puts '-' * 10 | ||
puts "Michigan's abbreviation is: #{states['Michigan']}" | ||
puts "Florida's abbreviation is: #{states['Florida']}" | ||
|
||
# do it by using the state then cities dict | ||
puts '-' * 10 | ||
puts "Michigan has: #{cities[states['Michigan']]}" | ||
puts "Florida has: #{cities[states['Florida']]}" | ||
|
||
# puts every state abbreviation | ||
puts '-' * 10 | ||
states.each do |state, abbrev| | ||
puts "#{state} is abbreviated #{abbrev}" | ||
end | ||
|
||
# puts every city in state | ||
puts '-' * 10 | ||
cities.each do |abbrev, city| | ||
puts "#{abbrev} has the city #{city}" | ||
end | ||
|
||
# now do both at the same time | ||
puts '-' * 10 | ||
states.each do |state, abbrev| | ||
city = cities[abbrev] | ||
puts "#{state} is abbreviated #{abbrev} and has city #{city}" | ||
end | ||
|
||
puts '-' * 10 | ||
# by default ruby says "nil" when something isn't in there | ||
state = states['Texas'] | ||
|
||
if !state | ||
puts "Sorry, no Texas." | ||
end | ||
|
||
# default values using ||= with the nil result | ||
city = cities['TX'] | ||
city ||= "Does Not Exist" | ||
puts "The city for the state 'TX' is: #{city}" |