Skip to content

Instantly share code, notes, and snippets.

@zr-tex8r
Created July 15, 2012 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zr-tex8r/3114906 to your computer and use it in GitHub Desktop.
Save zr-tex8r/3114906 to your computer and use it in GitHub Desktop.
To reinvent the if expression as method call
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
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