Topic: calculator program help

I'm trying to make a simple RPN calculator that reads in regular expressions from a file and evaluates them to execute code. Currently I have these regular expressions stored in an array of class objects that have 2 data objects (1. The regex itself and 2. The block of code that should be executed when a match is found). An example of one of the read in regex's is below:
[0-9]+
lambda {|input| $myStack.push(input)}

Now, I get input from the user and compare that string to all the regular expressions in my array. When a match is found, the code is evaluated. So far it is working by entering in input one by one. Code and an example are below.

while input = gets
  for i in 0..$regexArray.length-1
    if ( input =~ Regexp.new($regexArray(i).regex) )
      eval($regexArray(i).code).call(input)
    end
  end
end

Example:
5
4
+
print

will give "9" as it should. However, I want to make it so I can enter input in one line like:
5 4 + print

I've tried matching the input string with the regex with: myMatch = regex.match(input)
but when I enter a string such as "123 456" only the last part ("456") is matched when I need to first match the ("123"). Any help would be appreciated.

Re: calculator program help

I think you just need to research regex's more

If you want to match this pattern

operand operand operator

You'd need three parts to the regex, and realize that the return will be an array of matches

i.e.
pat = /[0-9]+ [0-9]+ +|-/

matches = pat.match("5 4 +")

matches[0] = "5"
matches[1] = "4"
matches[2] = "+"

That said,  if you want to build a truly robust and flexible input parser like that  I'd look into  Ruby-lex and Ruby-yacc ,  it will get ugly fast if you try it all with Regex,  IMHO

http://i.loveruby.net/en/projects/racc/

http://raa.ruby-lang.org/project/ruby-yacc/

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: calculator program help

Here is a simple RPN calculator done in Ruby without using yacc/lex

http://www.math.bas.bg/bantchev/place/rpn/rpn.ruby.html

Pretty slick,  I have to take back what I said about doing it ONLY using regex!

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: calculator program help

Thanks for the reply! I'll check out those links!