Ruby returning integer-only when item is in an array -
i'm creating reverse polish notation calculator 'warm-up test' school. i've nailed it. issue i'm coming across when run myself, see integer returned (which desired). when plug school's rspec checker returns data in array, it's flagged incorrect.
to fix, built queue.each statement on end. tried in few different positions, not seem matter. there bigger concept extract answer out of array format when evaluate returns answer?
class rpncalculator def evaluate(string) holding = [] queue = [] string = string.split(" ").to_a #jam string array - break on spaces string.each |x| if x.match(/\d/) #number checker. if true throw in queue. queue << x.to_i #convert number string elsif x.match(/\+/) #math operator checker holding << queue[-2] + queue[-1] #grab queue's last 2 & replace w/ result queue.pop(2) queue << holding[-1] elsif x.match(/\-/) holding << queue[-2] - queue[-1] queue.pop(2) queue << holding[-1] elsif x.match(/\*/) holding << queue[-2] * queue[-1] queue.pop(2) queue << holding[-1] else end end return queue.each { |x| puts x.to_i} # [-1] in string, queue holds answer end end thank in advance time,
your method (without queue.each) returning result of string.each.
if want return queue, need do that.
class rpncalculator def evaluate(string) holding = [] queue = [] string = string.split(" ").to_a #jam string array - break on spaces string.each |x| #... end queue[0] # return final result, stored in queue end end
Comments
Post a Comment