Skip to content

Instantly share code, notes, and snippets.

@ruxandrafed
Created September 2, 2015 22:13
Show Gist options
  • Select an option

  • Save ruxandrafed/dbaaad54f5e1955d26de to your computer and use it in GitHub Desktop.

Select an option

Save ruxandrafed/dbaaad54f5e1955d26de to your computer and use it in GitHub Desktop.
@states = Hash.new { |h, k| h[k][1] = []}
@states = {
OR: ['Oregon', ['Portland', 'Jacksonville']],
FL: ['Florida', ['Miami']],
CA: ['California', ['San Jose', 'San Francisco', 'Monterrey']],
NY: ['New York', ['New York City', 'Long Island']],
MI: ['Michigan', ['Detroit']]
}
# Task 1: add 2 additional states after definition
@states[:AK] = ['Alaska', ['Sitka', 'Juneau']]
@states[:CO] = ['Colorado', ['Utah']]
# Task 2: new hash cities with arrays of cities as values
# @cities = {
# OR: ['Portland', 'Jacksonville'],
# CA: ['San Jose', 'San Francisco', 'Monterrey'],
# CO: ['Utah']
# }
# Task 3: new method describing states
def describe_state(state_code)
state_code = state_code.intern
if @states.has_key?(state_code)
"#{state_code} is for #{@states[state_code][0]}. It has #{@states[state_code][1].size} major cities: #{@states[state_code][1].join(", ")}"
else
puts "Can't find #{state_code}"
end
end
# Task 4: new hash for defining taxes
@taxes = {
OR: 0,
FL: 6,
CA: 7.5,
NY: 4,
MI: 6
}
# Task 5: new method calculating tax
def calculate_tax(state_code, amount)
state_code = state_code.intern
if @states.has_key?(state_code)
amount = amount.to_f
tax = amount * @taxes[state_code] / 100
else
puts "Can't find #{state_code}"
end
end
# Task 6: new method find_state_for_city
def find_state_for_city(city_name)
# Filtering hash to keep only key-value pairs where city name is found in value (array)
state_name = @states.select {|k, v| v[1].include?(city_name)}
state_name.keys
end
# Output hashes for inspection
puts @states.inspect
puts @cities.inspect
puts "\n"
# Testing describe_state method
puts describe_state('HI')
puts describe_state('AK')
puts describe_state('OR')
puts "\n"
# Testing calculate_tax method
puts calculate_tax('OR', 100)
puts calculate_tax('CA', 100)
puts calculate_tax('CA', 200.75)
puts calculate_tax('AB', 200)
puts "\n"
# Testing find_state_for_city method
puts find_state_for_city('Utah')
puts find_state_for_city('Portland')
puts find_state_for_city('San Jose')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment