#!/usr/bin/env ruby problem = 3 input = File.readlines("#{problem}.input").join enabled = true result = input .scan(/mul\(\d{1,3},\d{1,3}\)|do\(\)|don't\(\)/) .map do |cmd| case cmd when "do()" enabled = true; nil when "don't()" enabled = false; nil when /mul/ if enabled cmd.scan(/(\d{1,3}),(\d{1,3})/).flatten.map(&:to_i).inject(1, :*) end end end.compact.sum puts result