#!/usr/bin/env ruby # # Calculator # # See file for options # # Created: Mon Jan 29 09:04:14 2007 # require 'net/http' require 'cgi' def scan(page, re, host = "www.google.com") h = Net::HTTP.new(host, 80) resp, data = h.get(page, nil) if resp.message == "OK" data.scan(re) { |y| yield y} else puts "ERROR: #{resp}" end end ########## Main ########## puts "Type math expressions or 'q' to quit or 'u' to remove units" puts buffer = 0 while true do print buffer.to_s + " > " cmd = STDIN.gets.chomp # remove space from the front and back cmd = cmd.gsub(/^\s+/,"") cmd = cmd.gsub(/\s+$/,"") # quit? break if /^q/i.match cmd # remove the units? if /^u$/.match cmd then buffer = buffer.gsub(/\s.*/,"") next end # numbers are just numbers if /^\+?\-?[\d\.e]+$/.match cmd then buffer = cmd next end # use the buffer if the command starts with a function and put the # buffer in parens funs = ["sin","cos","tan","isin","icos","itan","sqrt","isqrt"] funs.each do |x| if cmd == x then cmd = x + "(" + buffer + ")" break end end # use the buffer if the command starts with an operator and put the # buffer in front ops = ["\\+","-","\\/","\\*","%","\\^"] ops.each do |x| if /^#{x}/.match cmd then cmd = buffer + " " + x break end end # if we just say 'in ...' add the buffer to the front # and make this the command if /^in /.match cmd then cmd = buffer + " " + cmd end page = "/search?q=" + CGI.escape(cmd) scan(page, /images\/calc_img\.gif.*[^\=]+\=\s*([^<]+)\s*<\/b>/im) { |result| buffer = result[0] } end