A small, dependency-free Result type for Ruby, modelled after Rust's Result.
Result represents either a successful outcome (Result::Ok, wrapping a value)
or a failed one (Result::Err, wrapping an error). It lets you chain operations
explicitly, without raising exceptions for control flow.
This gem is not published to RubyGems.org. Install it directly from git by adding the following line to your application's Gemfile:
gem "result", github: "nunsez/result_rb"If bundler is not being used to manage dependencies, install the gem from git by executing:
gem install result --source https://github.com/nunsez/result_rbThen require "result" in your code.
Build a result with either of the two variants:
require "result"
ok = Result::Ok.new(42)
err = Result::Err.new("something went wrong")Including Result::Mixin gives you the value constructors for a more concise
style — both the success value and the error carry meaning:
class Calculator
include Result::Mixin
def divide(a, b)
b.zero? ? Err(:division_by_zero) : Ok(a / b)
end
end
result = Calculator.new.divide(10, 0)
result.ok? # => false
result.err # => :division_by_zeroCombine and transform results with the standard combinator methods:
ok.map { |v| v * 2 } # => Result::Ok(84)
err.map_err { |e| e.upcase } # => Result::Err(SOMETHING WENT WRONG)
ok.and { Ok(t) } # short-circuits on Err
err.or { Ok(:recovery) } # short-circuits on OkExtract the value, or handle the failure, with the terminating operations:
result.ok? # => true / false
result.err? # => true / false
result.unwrap # returns the value, raises on Err
result.expect("the value") # returns the value, raises with a message on Err
result.unwrap_or { fallback } # returns value or the block result
result.ok # value or nil
result.err # error or nilAfter checking out the repo, run bin/setup to install dependencies. Then, run
rake test to run the tests. You can also run bin/console for an interactive
prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install.
Bug reports and pull requests are welcome on GitHub at https://github.com/nunsez/result_rb.