Skip to content

Instantly share code, notes, and snippets.

@mungruby
Created May 22, 2012 07:36
Show Gist options
  • Save mungruby/2767363 to your computer and use it in GitHub Desktop.
Save mungruby/2767363 to your computer and use it in GitHub Desktop.
Nested Hash with Database
module MockRetriever
def self.fetch_rows database, table
return ["#{rand(100)} Main St.", "#{rand(100)} Second Ave.", "#{rand(100)} Peach Ln."]
end
end
module AddressHandler
# @addresses = Hash.new( {} ) # old code - returns the SAME hash, not a new hash
@addresses = Hash.new { |hash, key| hash[key] = {} }
def self.addresses state, city
if value = @addresses[state][city]
puts "fetched stored value"
value
else
puts "storing new value"
@addresses[state][city] = MockRetriever.fetch_rows state, city
end
end
end
if __FILE__ == $0
p AddressHandler.addresses 'alaska', 'anchorage'
p AddressHandler.addresses 'washington', 'vancouver'
p AddressHandler.addresses 'british columbia', 'vancouver'
p AddressHandler.addresses 'washington', 'vancouver'
end
@mungruby
Copy link
Author

With @addresses = Hash.new( {} ):

storing new value
["7 Main St.", "48 Second Ave.", "31 Peach Ln."]
storing new value
["98 Main St.", "87 Second Ave.", "39 Peach Ln."]
fetched stored value
["98 Main St.", "87 Second Ave.", "39 Peach Ln."]
fetched stored value
["98 Main St.", "87 Second Ave.", "39 Peach Ln."]

With @addresses = Hash.new { |hash, key| hash[key] = {} }

storing new value
["67 Main St.", "76 Second Ave.", "76 Peach Ln."]
storing new value
["67 Main St.", "8 Second Ave.", "8 Peach Ln."]
storing new value
["98 Main St.", "55 Second Ave.", "98 Peach Ln."]
fetched stored value
["67 Main St.", "8 Second Ave.", "8 Peach Ln."]

The latter is the desired behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment