Skip to content

Instantly share code, notes, and snippets.

@kmdsbng
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save kmdsbng/3ebd28dc47c3baf06dc9 to your computer and use it in GitHub Desktop.

Select an option

Save kmdsbng/3ebd28dc47c3baf06dc9 to your computer and use it in GitHub Desktop.
require 'rmaybe'
# This code returns "C"
"a b c".split[2].upcase # => "C"
# And if you use maybe. ... .end chain, you can get same result.
"a b c".maybe.split[2].upcase.end # => "C"
# This code causes NoMethodError.
"a b c".split[3].upcase
# ~> /home/kameda/work/maybe_test.rb.rubyeval:9:in `<main>': undefined method `upcase' for nil:NilClass (NoMethodError)
# But if you use maybe. ... .end chain, you can get nil without exception. Why?
"a b c".maybe.split[3].upcase.end # => nil
# Because Maybe class hide real value, and proxy
# method call to real value.
"a b c" # => "a b c"
# This code creates Maybe instance that holds "a b c" as real value.
"a b c".maybe # => #<Maybe:0x00000001d78e98>
# You can check this behavior with pop real value with `end` method.
# Maybe#end returns real value.
"a b c".maybe.end # => "a b c"
# Maybe instance proxy `split` method call to "a b c"(real value),
# `"a b c".split` returns ["a", "b", "c"].
# So, Maybe instance returns new Maybe instance that holds ["a", "b", "c"] as real value.
"a b c".maybe.split # => #<Maybe:0x00000001d7f4a0>
# You can check this behavior with pop real value with `end` method.
"a b c".maybe.split.end # => ["a", "b", "c"]
# Maybe instance proxy `[3]` method call to ["a", "b", "c"](real value),
# `["a", "b", "c"][3]` returns nil
# So, Maybe instance returns Never instance.
"a b c".maybe.split[3] # => #<Never:0x00000001d7df88>
# Never instance doesn't proxy any method call, and returns Never instance to any method call withoud `end` method.
# So, Never#upcase returns Never instance.
"a b c".maybe.split[3].upcase # => #<Never:0x00000001d7d448>
# Never#end returns nil always.
"a b c".maybe.split[3].upcase.end # => nil
# You can find Rmaybe's source code at Github.
# Source code's size is about only 50 lines.
# Check it!
# https://github.com/kmdsbng/rmaybe/blob/master/lib/rmaybe.rb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment