Created
December 1, 2019 18:19
-
-
Save havenwood/b0c6bdd59be549a6bb701b575480e55b to your computer and use it in GitHub Desktop.
Playing with chaining #then on a Swift-like Optional
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
# frozen_string_literal: true | |
class Optional | |
attr_reader :value | |
def initialize(value) | |
@value = value | |
end | |
def then(&block) | |
return enum_for __method__ unless block_given? | |
return self.class.none if @value.nil? | |
@value.public_send __method__, &block | |
end | |
class << self | |
def none | |
new nil | |
end | |
alias some new | |
end | |
end | |
a = Optional.some(42) | |
b = Optional.some(a) | |
c = Optional.some(b) | |
d = Optional.some(c) | |
d.then.first | |
#=> 42 | |
f = Optional.none | |
g = Optional.some(f) | |
g.then.first | |
#=> nil | |
Pickle = Struct.new :jar | |
Jar = Struct.new :label | |
Label = Struct.new :words | |
label = Optional.some Label.new 'Bubbies' | |
jar = Optional.some Jar.new label | |
pickle = Optional.some Pickle.new jar | |
pickle.then(&:jar).then(&:label).then(&:words) | |
#=> "Bubbies" | |
no_jar = Optional.none | |
another_pickle = Optional.some Pickle.new no_jar | |
another_pickle.then(&:jar).then(&:label).then(&:words) | |
#=> #<Optional:... @value=nil> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment