#!/usr/bin/env ruby # frozen_string_literal: true require "stringio" class Main def run num_map = [] $stdin.each_line do |line| num_map << line.chomp.chars end problems = Hash.new(0) count = 0 problems[count] = Hash.new(0) num_map.transpose.each do |chars| if chars.uniq == [" "] count += 1 problems[count] = Hash.new(0) next end num_str = StringIO.new chars.each do |ch| if ch.match?(/\d/) num_str.write(ch) else problems[count][:op] = [] unless problems[count].key?(:op) problems[count][:op] << ch.to_sym unless ch == " " end end problems[count][:nums] = [] unless problems[count].key?(:nums) problems[count][:nums] << num_str.string.to_i unless num_str.string.empty? end @sum = 0 problems.each do |_, data| @sum += recurse(data[:nums], data[:op].first) end puts @sum end def recurse(nums, op) return nums.first if nums.size == 1 num1, num2 = nums.shift(2) case op.to_sym when :+ nums.unshift(num1 + num2) when :- nums.unshift(num1 - num2) when :* nums.unshift(num1 * num2) when :/ if nums[1] == 0 raise "Division by zero" end nums.unshift(num1 / num2) end recurse(nums, op) end end Main.new.run