Created
March 6, 2010 19:02
-
-
Save eqdw/323873 to your computer and use it in GitHub Desktop.
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
puts "Welcome to uber-calculator" | |
puts "Please enter commands in the format:" | |
puts "\tX op Y" | |
puts "Prefix 0x for hex, 0b for binary" | |
puts "... hell, lets do octal too!" | |
puts "Type q(uit) to, y'know, QUIT!" | |
puts "Output in base 10, change output base with base = N" | |
class String | |
def to_10 | |
base = nil | |
if self =~ /^0b([01]+)/ | |
return $1.to_i(2) | |
elsif self =~ /^0x([\dabcdefABCDEF]+)/ | |
return $1.to_i(16) | |
elsif self =~ /^0([01234567]+)/ | |
return $1.to_i(8) | |
elseif self =~ /[\d]+/ | |
return to_i | |
else | |
raise "Frak!" | |
end | |
end | |
end | |
while(print ">>"; input = gets and input !~ /q(uit)?/i) | |
tokens = input.split(/\s+/) | |
if tokens.size != 3 | |
puts "uh uh uh, didn't say the magic word!" | |
next | |
end | |
first, op, second = tokens | |
if first=="base" and op=="=" | |
begin | |
$base = second.to_10 | |
raise "That's WAYY too big (that's what she said)" if $base > 36 | |
rescue | |
$base = 10 | |
end | |
puts "Base set to #{$base}" | |
next | |
end | |
unless %w|+ - * /|.include? op | |
puts "I don't even know what the hell you are trying to do, try one of these: + - * /" | |
next | |
end | |
begin | |
answer = first.to_10.send(op.to_sym, second.to_10) | |
puts "#=> #{answer.to_s($base)}" | |
rescue | |
puts "So, there was an error, and we lost both your numbers" | |
end | |
end | |
puts "OK, LOVE YOU BYE!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment