Skip to content

Instantly share code, notes, and snippets.

@dnagir
Last active October 18, 2017 00:58
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 dnagir/9134d1b498f8ed3d8b1cb75dc6d9411f to your computer and use it in GitHub Desktop.
Save dnagir/9134d1b498f8ed3d8b1cb75dc6d9411f to your computer and use it in GitHub Desktop.
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