Skip to content

Instantly share code, notes, and snippets.

@zr-tex8r
Created July 29, 2012 03:03
Show Gist options
  • Save zr-tex8r/3195881 to your computer and use it in GitHub Desktop.
Save zr-tex8r/3195881 to your computer and use it in GitHub Desktop.
Ruby: Weird if-expression
load 'wix.rb'
# FizzBuzz
1.upto(20) do |n|
Wix.if { n % 3 == 0 }.then {
print "Fizz"
}.if { n % 5 == 0 }.then {
print "Buzz"
}.else {
print n
}
puts
end
# NabeAzz
1.upto(40) do |n|
Wix.if { n % 3 == 0 }
.thenorif { /3/ =~ n.to_s }
.then { print "<aho>" }
.anyway { print n }
.then { print "</aho>" }
.anyway { print " " }
end
puts
module Wix
class State
def initialize(accum, prev)
@accum, @prev = accum, prev
end
def if
next_state(yield)
end
def thenandif
next_state(@prev && yield)
end
def thenorif
next_state(@prev || yield)
end
def ifaboveandif
next_state(@accum && yield)
end
def ifaboveorif
next_state(@accum || yield)
end
def elseandif
next_state(!@accum && yield)
end
alias_method :elsif, :elseandif
def elseorif
next_state(!@accum || yield)
end
def next_state(curr)
State.new(@accum || curr, curr)
end
private :next_state
def then(&blk)
dispatch(@prev, &blk)
end
def ifabove(&blk)
dispatch(@accum, &blk)
end
def else(&blk)
dispatch(!@accum, &blk)
end
def anyway(&blk)
dispatch(true, &blk)
end
def dispatch(curr, &blk)
if curr then yield end
self
end
private :dispatch
end
InitState = State.new(false, true)
def self.if(&blk)
InitState.if(&blk)
end
def self.anyway(&blk)
InitState.anyway(&blk)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment