Skip to content

Instantly share code, notes, and snippets.

@zr-tex8r
Created July 20, 2012 07:58
Show Gist options
  • Save zr-tex8r/3149451 to your computer and use it in GitHub Desktop.
Save zr-tex8r/3149451 to your computer and use it in GitHub Desktop.
“If function” implemented without using existing if-expression
# FizzBuzz program.
require 'iffunction'
1.upto(20) do |n|
_if(n % 15 == 0) {
puts "FizzBuzz"
}.elsif(n % 3 == 0) {
puts "Fizz"
}.elsif(n % 5 == 0) {
puts "Buzz"
}.else {
puts n
}
end
# iffunction.rb
class NilClass
def _choose(tval, fval)
fval
end
end
class FalseClass
def _choose(tval, fval)
fval
end
end
class Object
def _choose(tval, fval)
tval
end
end
module IfFunc
Noop = Proc.new {}
def self._if(cond, blk)
cond._choose(blk, Noop).call
cond._choose(Done, Notyet)
end
Notyet = Object.new
class << Notyet
def elsif(cond, &blk)
IfFunc._if(cond, blk)
end
def else(&blk)
blk.call
nil
end
end
Done = Object.new
class << Done
def elsif(cond, &blk)
Done
end
def else(&blk)
nil
end
end
end
def _if(cond, &blk)
IfFunc._if(cond, blk)
end
# EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment