Last active
August 29, 2015 14:04
-
-
Save joker1007/ca7861b3990195f1663a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Guardable | |
def initialize(obj) | |
@obj = obj | |
end | |
def method_missing(method_name, *args, &block) | |
return @obj if @obj.nil? | |
@obj.send(method_name, *args, &block) | |
end | |
end | |
module NilGuard | |
refine Object do | |
def & | |
Guardable.new(self) | |
end | |
end | |
refine Array do | |
def & | |
Guardable.new(self) | |
end | |
end | |
refine NilClass do | |
def & | |
Guardable.new(self) | |
end | |
end | |
end | |
using NilGuard | |
p "hoge".&.upcase.&.gsub(/H/, "n") | |
p %w(foo bar).&.map {|str| nil}.each {|n| n.&.to_i}.compact |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment