Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created December 1, 2019 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/b0c6bdd59be549a6bb701b575480e55b to your computer and use it in GitHub Desktop.
Save havenwood/b0c6bdd59be549a6bb701b575480e55b to your computer and use it in GitHub Desktop.
Playing with chaining #then on a Swift-like Optional
# 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