Last active
October 7, 2015 15:57
-
-
Save Denommus/3189739 to your computer and use it in GitHub Desktop.
A calculator using reverse polish notation, written in Ruby
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
#!/usr/bin/env ruby | |
arr = [] | |
$stdin.each_line do |n| | |
n.chop! | |
break if %w(exit quit).include?(n) | |
arr << (/[[:digit:]]+/ === n ? n.to_f : n.to_sym) | |
if arr.last.is_a?(Symbol) | |
if arr.length < 3 | |
puts 'Not enough numbers in stack.' | |
arr.pop | |
else | |
fun, op2, op1 = arr.pop, arr.pop, arr.pop | |
arr << op1.send(fun, op2) | |
end | |
end | |
puts arr | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment