#!/usr/bin/env ruby data = File.read("data.txt") valid = data.scan(/(mul\(\d+,\d+\)|don't\(\)|do\(\))/) p valid sum = 0; act = true ops = valid.map do |operation| if operation[0] == "don't()" act = false 0 elsif operation[0] == "do()" act = true 0 elsif act operation[0].gsub(/[^\d*,]/, "").to_s.split(",").map(&:to_i).reduce(&:*) else 0 end end p ops.sum