A Ruby port of Scala's Option monad. Tries to be faithful but also pragmatic in RE: to duck typing.
Add this line to your application's Gemfile:
gem 'option'
And then execute:
$ bundle
Or install it yourself as:
$ gem install option
Generally, you want to use the Option(A) wrapper method to box your value. This will make the right decision as to what your initial value should be:
foo=Option("bar")This will allow you to now manipulate the value in the box via various means:
# get the valuefoo.get#=> "bar"# return a default if the box is NoneNone.get_or_else{"default"}#=> "default"# map the value to another optionfoo.map{ |v| v.upcase}#=> Some("BAR")# does the value meet a requirement?foo.exists?{ |v| v == "bar"}#=> true# return the value or nil depending on the statefoo.or_nil#=> "bar"# chain valuesfoo.map{ |v| v * 2}.map{ |v| v.upcase}.get_or_else{"missing"}#=> BARBAR# attempt to extract a value but default if NoneNone.fold(->{"missing"}){ |v| v.upcase}#=> missing# filter values returning an optionfoo.filter{ |v| v == "baz"}#=> None# Side-effectsfoo.inside{ |v| v.upcase!}#=> Some("BAR")# use in a for loopforvalueinfooputsvalue#=> barend- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Implement your feature. Patches not considered without accompanying tests.
- Commit your changes (
git commit -am 'Added some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request