Skip to content

Instantly share code, notes, and snippets.

@dudo
Created January 19, 2018 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dudo/ab8f9be03b0904e057d964e0695db6dc to your computer and use it in GitHub Desktop.
Save dudo/ab8f9be03b0904e057d964e0695db6dc to your computer and use it in GitHub Desktop.
class PostFixCalculator
attr_accessor :list, :original_list
def initialize(list)
@original_list = list
@list = list.split(' ')
end
def evaluation
list.each_with_object(stack=[]) do |x,o|
case x
when /\d/
o.push(x)
when "-", "/", "*", "+", "**", '%'
result = process_operands(o.pop(2), x)
o.push(result)
end
end
raise 'ArgumentError' if stack.count > 1
stack.first
end
def print_result
puts "#{original_list} = #{evaluation}"
end
def self.tests_passing?
[
self.new('1 2 +').evaluation == 3,
self.new('10 5 -').evaluation == 5,
self.new('3 2 *').evaluation == 6,
self.new('5 2 **').evaluation == 25,
self.new('1 2.0 %').evaluation == 1,
self.new('1 2 /').evaluation == 0,
self.new('1 2.0 /').evaluation == 0.5,
self.new('1 2 3 + -').evaluation == -4,
].all?
end
private
def process_operands(operands=[], operator)
operands.map{ |i| Integer(i) rescue Float(i) }.inject(operator)
end
end
raise 'FaultyCalculator' unless PostFixCalculator.tests_passing?
puts PostFixCalculator.new(ARGV[0]).print_result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment