From 8197b50a5728d2e622dac5da7908c96e38a3e53c Mon Sep 17 00:00:00 2001 From: Rikuoh Date: Tue, 23 Jul 2024 22:48:32 +0900 Subject: [PATCH] =?UTF-8?q?=E5=8F=B3=E5=AF=84=E3=81=9B=E3=81=AE=E5=87=A6?= =?UTF-8?q?=E7=90=86=E3=82=92=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wc.rb | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/wc.rb b/wc.rb index afd18d6..7cc5787 100644 --- a/wc.rb +++ b/wc.rb @@ -1,3 +1,4 @@ + # frozen_string_literal: true require 'optparse' @@ -15,20 +16,28 @@ def parse_options end def input_stream_sources(input_sources, options) - total_stats = { lines: 0, words: 0, bytes: 0 } - max_widths = { lines: 0, words: 0, bytes: 0 } - - input_sources.each do |source| - stats = input_stream(source) - total_stats = update_totals(total_stats, stats) - max_widths = update_max_widths(max_widths, stats) + all_stats = input_sources.map { |source| [source, input_stream(source)] } + total_stats = all_stats.reduce({ lines: 0, words: 0, bytes: 0 }) do |total, (_, stats)| + update_totals(total, stats) + end + max_widths = calculate_max_widths(all_stats, total_stats) + + all_stats.each do |source, stats| result = format_result(stats, max_widths, options) print_result(result, source) end - + print_total(total_stats, max_widths, options) if input_sources.size > 1 end +def calculate_max_widths(all_stats, total_stats) + max_widths = { lines: 0, words: 0, bytes: 0 } + (all_stats.map(&:last) + [total_stats]).each do |stats| + max_widths = update_max_widths(max_widths, stats) + end + max_widths +end + def input_stream(source) if source == '-' count_file_stats(ARGF)