Skip to content

Instantly share code, notes, and snippets.

@dnagir

dnagir/maybe.rb

Last active Oct 18, 2017
Embed
What would you like to do?
Minimal Ruby Maybe monad
require 'singleton'
module Maybe
class Just < BasicObject
attr_reader :value
def initialize(value)
@value = value
end
def present?
true
end
end
class Nothing < BasicObject
include ::Singleton
def present?
false
end
end
def self.just(value)
Just.new(value)
end
def self.nothing
Nothing.instance
end
end
puts Maybe.just('foo').value # "foo"
puts Maybe.nothing.value rescue puts "No value on nothing"
puts Maybe.just('foo').to_s rescue puts "Can't call random stuff on Maybe - unwrap using #value"
def use_maybe(maybe)
if maybe.present?
puts maybe.value
else
puts "no, no, cannot use it"
end
end
use_maybe Maybe.just('foo')
use_maybe Maybe.nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment