Skip to content

Instantly share code, notes, and snippets.

@aoitaku
Created February 8, 2015 12:17
Show Gist options
  • Save aoitaku/dcaa960eb813b6b0d321 to your computer and use it in GitHub Desktop.
Save aoitaku/dcaa960eb813b6b0d321 to your computer and use it in GitHub Desktop.
DSL で IF文
require 'pp'
$dsl = []
$if_stack = []
def IF(cond=Proc.new)
$if_stack << []
$if_stack.last << {}
$if_stack.last.last[:cond] = cond
end
def THEN(expr=Proc.new)
$if_stack.last.last[:expr] = expr
end
def ELSIF(cond=Proc.new)
$if_stack.last << {}
$if_stack.last.last[:cond] = cond
end
def ELSE(expr=Proc.new)
$if_stack.last << {}
$if_stack.last.last[:cond] = -> { true }
$if_stack.last.last[:expr] = expr
end
def ENDIF
$dsl << {if: $if_stack.pop}
end
def Object.const_missing(name)
send(name)
end
def do_inst(inst)
symbol, stmt = *inst.keys, *inst.values
case symbol
when :if
do_if(stmt)
end
end
def do_if(if_stmt)
if_stmt.any? {|stmt|
if stmt[:cond].()
stmt[:expr].()
true
else
false
end
}
end
dice = rand(6) + 1
IF { dice == 6 }
THEN {
puts "#{dice}!"
}
ELSIF { dice == 1 }
THEN {
puts "#{dice}..."
}
ELSE {
puts 'else'
dice = rand(6) + 1
IF { dice == 6 }
THEN {
puts "#{dice}!"
}
ELSIF { dice == 1 }
THEN {
puts "#{dice}..."
}
ELSE {
puts 'else'
dice = rand(6) + 1
IF { dice == 6 }
THEN {
puts "#{dice}!"
}
ELSIF { dice == 1 }
THEN {
puts "#{dice}..."
}
ELSE {
puts dice
}
ENDIF
}
ENDIF
}
ENDIF
pp $dsl
$dsl.each(&method(:do_inst))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment