Created
July 20, 2012 07:58
-
-
Save zr-tex8r/3149451 to your computer and use it in GitHub Desktop.
“If function” implemented without using existing if-expression
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
# 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 |
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
# 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