# Postfix to Infix (#148)

**URL:** <https://www.ruby-forum.com/t/postfix-to-infix-148/121961>\
**Category:** Ruby\
**Created:** [December 3, 2007, 1:14pm UTC](https://www.ruby-forum.com/t/postfix-to-infix-148/121961 "2007-12-03T13:14:12Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![SSSSSSSSSSSSS\_SSSSS](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/49beb7/32.png) [@SSSSSSSSSSSSS\_SSSSS](https://www.ruby-forum.com/u/SSSSSSSSSSSSS_SSSSS)\
**Post date:** [December 3, 2007, 1:14pm UTC](https://www.ruby-forum.com/t/postfix-to-infix-148/121961/1 "2007-12-03T13:14:12Z")

</div>

Sorry, in previous post I forgot about parenthess in case of - and /.

# this program understands simple operations and also sin, cos, tg and

ctg

# to use, provide string in RPN as argument

# example: ruby postf2inf ‘3 5 + sin 5 3 cos + /’

# result in “sin(3 + 5) / (5 + cos(3))”

str\_postf=ARGV[0]  
str\_inf=[]  
prior = {’+’=\>1,’-’=\>1,’\*’=\>3,’/’=\>3}  
stack = str\_postf.split(’ ')

0.upto stack.size-1 do |l|  
if [’+’,’-’,’\*’,’/’].include?(stack[l])  
arg1 = str\_inf.pop  
arg2 = str\_inf.pop  
arg1[1]=’(’+arg1[1]+’)’ if arg1[0]\<prior[stack[l]]  
arg1[1]=’(’+arg1[1]+’)’ if [’-’,’/’].include?(stack[l]) and  
arg1[0]==prior[stack[l]]  
arg2[1]=’(’+arg2[1]+’)’ if arg2[0]\<prior[stack[l]]  
str\_inf.push([prior[stack[l]] , arg2[1]+" #{stack[l]} "+arg1[1]])  
elsif [‘sin’,‘cos’,‘tg’,‘ctg’].include?(stack[l])  
str\_inf.push([5 , “#{stack[l]}(#{str\_inf.pop[1]})”])  
else  
str\_inf.push([5,stack[l]])  
end  
end

p str\_inf.pop[1]
