Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class StrawpigScript
- attr_accessor :script
- TOKENS = ["+", "-", "*", "/", "x", "integer", "float"]
- def initialize(length)
- intermediate = length.times.inject("") {|program, i| program + " #{TOKENS.sample}"}
- with_ints = intermediate.gsub(/integer/) {rand(21)-10}
- @script = with_ints.gsub(/float/) {(rand*20.0-10.0).round(2)}
- end
- def evaluate(x)
- stack = []
- @script.split.each do |token|
- begin
- case token
- when /([-+]?[0-9]*\.?[0-9]+)/ # float
- stack.push($1.to_f)
- when /[-+]?[0-9]+/ # integer
- stack.push($1.to_i)
- when "+", "-", "*"
- raise ArgumentError, "short stack" if stack.length < 2
- arg1, arg2 = stack.pop(2)
- result = arg1.send(token.intern, arg2)
- stack.push(result)
- when "/"
- raise ArgumentError, "short stack" if stack.length < 2
- arg1, arg2 = stack.pop(2)
- result = (arg2 == 0) ? 0 : arg1.send(token.intern, arg2)
- stack.push(result)
- when "x"
- stack.push x
- else
- # ignore unrecognized tokens
- end
- rescue ArgumentError => e
- # don't pop items from the stack
- end
- end
- return stack[-1] || 1000000 # the top stack item, or a huge value if it's missing
- end
- end
Add Comment
Please, Sign In to add comment