Skip to content

Instantly share code, notes, and snippets.

@leeacto
Last active December 19, 2015 05:19
Show Gist options
  • Save leeacto/5903720 to your computer and use it in GitHub Desktop.
Save leeacto/5903720 to your computer and use it in GitHub Desktop.
class RPNCalculator
def evaluate(string)
return string.to_i if string.split(' ').count == 1
sarray = string.split(' ')
#Check for Valid setup
syms = 0
nums = 0
valchars = true
sarray.each do |c|
syms += 1 if c =~ /[\D]/ && c.length == 1
nums += 1 if c =~ /[\d]/
if c =~ /[a-zA-Z]/ then
valchars = false
break
end
end
raise ArgumentError.new("The String contains Invalid Characters") if valchars == false
raise ArgumentError.new("The String Does not contain the proper number of symbols/numbres") if nums - syms != 1
i = 1
until sarray[i] =~ /[\D]/ && sarray[i].length == 1 do
i +=1
end
if sarray[i] == '+'
sarray[i-2] = sarray[i-2].to_i + sarray[i - 1].to_i
elsif sarray[i] == '*'
sarray[i-2] = sarray[i-2].to_i * sarray[i - 1].to_i
else
sarray[i-2] = sarray[i-2].to_i - sarray[i - 1].to_i
end
sarray.delete_at(i)
sarray.delete_at(i-1)
evaluate(sarray.join(' '))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment