Either types with pattern matching
Ruby
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib
spec
.gitignore
.travis.yml
Gemfile
Gemfile.lock
LICENSE.md
README.md
Rakefile
either.gemspec

README.md

either

stop using exceptions for control flow with either types

Build Status Code Climate

An either can hold one of two possible things - a typical example would be either the successful result of a computation or an error explaining what went wrong.

By convention, a Left holds an error, while a Right holds the result of a successful computation.

Here's a simple example:

def divide x y
  y == 0 ? Left("Cannot divide by zero") : Right(x / y)
end

divide(4,2).match do |m|
  m.right { |res| puts "Division success: #{res}" }
  m.left  { |err| puts "Couldn't do this: #{err}" }
end
# The above will print "Division success: 2"

divide(4,0).match do |m|
  m.right { |res| puts "Division success: #{res}" }
  m.left  { |err| puts "Couldn't do this: #{err}" }
end
# The above will print "Couldn't do this: Cannot divide by zero"