Created
July 29, 2012 03:03
-
-
Save zr-tex8r/3195881 to your computer and use it in GitHub Desktop.
Ruby: Weird 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
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 |
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 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