Created
April 3, 2020 12:24
-
-
Save alex-lairan/f957c52de0ee88d73f5df8bd06dac49e to your computer and use it in GitHub Desktop.
MaybeHash
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
class Some | |
def initialize(value) | |
@value = value | |
end | |
def value | |
@value | |
end | |
end | |
class None | |
def initialize | |
end | |
def value | |
raise "error" | |
end | |
end | |
class MaybeHash | |
def initialize(hash) | |
@hash = hash | |
end | |
def [](key) | |
if @hash.has_key?(key) | |
Some.new(@hash[key]) | |
else | |
None.new() | |
end | |
end | |
end | |
hash = { | |
key: :value | |
} | |
hash = MaybeHash.new(hash) | |
pp hash[:key] | |
pp hash[:unknown_key] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment