2023-05-25 17:47:19 +02:00
|
|
|
# Lösung: Hashes und Blöcke
|
2023-05-23 09:19:31 +02:00
|
|
|
|
|
|
|
<div style="border: 1px solid grey;"><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br></div>```ruby
|
2023-05-25 17:47:19 +02:00
|
|
|
class Cache
|
|
|
|
def initialize(&callback)
|
|
|
|
@data = {}
|
|
|
|
@callback = callback
|
|
|
|
end
|
|
|
|
|
|
|
|
def add(key, value)
|
|
|
|
@data[key] = value
|
|
|
|
end
|
2023-05-23 09:19:31 +02:00
|
|
|
|
2023-05-25 17:47:19 +02:00
|
|
|
def [](key)
|
|
|
|
@data[key] = @callback.call(key) unless @data.has_key?(key)
|
|
|
|
@data[key]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
```
|