Created
July 15, 2012 04:00
-
-
Save zr-tex8r/3114906 to your computer and use it in GitHub Desktop.
To reinvent the if expression as method call
This file contains 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
module IfMethod | |
Done = Object.new | |
NotYet = Object.new | |
Noop = Proc.new {} | |
DoneWith = Object.new | |
def self.proc_if(cond, tblk) | |
if cond then | |
tblk.call | |
Done | |
else | |
NotYet | |
end | |
end | |
def self.proc_else(arg, fblk, &ret) | |
if arg.empty? then | |
fblk.call | |
nil | |
else | |
ret.call(arg[0]) | |
end | |
end | |
def Done.else(*arg, &fblk) | |
IfMethod.proc_else(arg, Noop) { |x| DoneWith } | |
end | |
def NotYet.else(*arg, &fblk) | |
IfMethod.proc_else(arg, fblk) { |x| x } | |
end | |
def DoneWith.if(&tblk) | |
Done | |
end | |
end | |
class Object | |
def if(&tblk) | |
IfMethod.proc_if(self, tblk) | |
end | |
end |
This file contains 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
load 'ifmethod.rb' | |
def test1(n) | |
(n < 10).if { | |
p 'small' | |
}.else(n < 100).if { | |
p 'medium' | |
}.else { | |
p 'big' | |
} | |
end | |
test1(3) | |
test1(33) | |
test1(333) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment