From bff969520fff95478c8137d53869e9fef7a6ffa0 Mon Sep 17 00:00:00 2001 From: Rikuoh Date: Thu, 25 Jul 2024 20:20:47 +0900 Subject: [PATCH] =?UTF-8?q?=E3=81=AA=E3=82=93=E3=81=8B=E3=82=82=E3=81=86?= =?UTF-8?q?=E3=82=81=E3=81=A1=E3=82=83=E3=81=8F=E3=81=A1=E3=82=83=E5=A4=89?= =?UTF-8?q?=E3=81=88=E3=81=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wc.rb | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/wc.rb b/wc.rb index 3e81c42..487da2b 100644 --- a/wc.rb +++ b/wc.rb @@ -3,12 +3,12 @@ require 'optparse' def main - options, input_sources = parse_options - all_stats = collect_all_stats(input_sources) - total_stats = calculate_total_stats(all_stats) - max_widths = calculate_max_widths(all_stats, total_stats) - print_all_stats(all_stats, max_widths, options) - print_all_stats([['合計', total_stats]], max_widths, options) if input_sources.size > 1 + options, sources = parse_options + file_stats = collect_file_stats(sources) + total_stats = calculate_total_stats(file_stats) + max_widths = calculate_max_widths(file_stats, total_stats) + print_file_stats(file_stats, max_widths, options) + print_file_stats([['合計', total_stats]], max_widths, options) if sources.size > 1 end def parse_options @@ -23,22 +23,22 @@ def parse_options [options, sources] end -def collect_all_stats(input_sources) - input_sources.map do |source| +def collect_file_stats(sources) + sources.map do |source| input = source.empty? ? ARGF.read : File.read(source) stats = { lines: input.lines.count, words: input.split.size, bytes: input.bytesize } [source, stats] end end -def calculate_total_stats(all_stats) - all_stats.reduce({ lines: 0, words: 0, bytes: 0 }) do |total, (_, stats)| +def calculate_total_stats(file_stats) + file_stats.reduce({ lines: 0, words: 0, bytes: 0 }) do |total, (_, stats)| total.merge(stats) { |_, a, b| a + b } end end -def calculate_max_widths(all_stats, total_stats) - (all_stats.map(&:last) + [total_stats]).each_with_object({ lines: 0, words: 0, bytes: 0 }) do |stats, max_widths| +def calculate_max_widths(file_stats, total_stats) + (file_stats.map(&:last) + [total_stats]).each_with_object({ lines: 0, words: 0, bytes: 0 }) do |stats, max_widths| max_widths.merge!(stats) { |_, max, stat| [max, stat.to_s.length].max } end end @@ -47,8 +47,8 @@ def format_result(stats, max_widths, options) %i[lines words bytes].map { |key| stats[key].to_s.rjust(max_widths[key]) if options[key] }.compact.join(' ') end -def print_all_stats(all_stats, max_widths, options) - all_stats.each do |source, stats| +def print_file_stats(file_stats, max_widths, options) + file_stats.each do |source, stats| result = format_result(stats, max_widths, options) puts "#{result} #{source}" end