Skip to content

Commit

Permalink
Exercise 39: Hashes, Oh Lovely Hashes
Browse files Browse the repository at this point in the history
  • Loading branch information
yellowflash2041 committed Oct 4, 2022
1 parent 92c7a36 commit 387f4f8
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions ex39.rb
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}"

0 comments on commit 387f4f8

Please sign in to comment.