From 66768a11ed63b167418c3c39fd40033962c51cee Mon Sep 17 00:00:00 2001 From: Rikuoh Tsujitani Date: Wed, 31 Jul 2024 15:10:33 +0900 Subject: [PATCH] =?UTF-8?q?=E3=81=95=E3=81=99=E3=81=8C=E3=81=AB=E3=81=93?= =?UTF-8?q?=E3=82=8C=E3=81=A7=E5=AE=8C=E6=88=90=E3=81=A8=E3=81=84=E3=81=86?= =?UTF-8?q?=E3=81=93=E3=81=A8=E3=81=AB=E3=81=97=E3=81=9F=E3=81=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wc.rb | 42 ++++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/wc.rb b/wc.rb index 47d5ba9..cd3d2c6 100644 --- a/wc.rb +++ b/wc.rb @@ -4,12 +4,12 @@ require 'optparse' def main options, filenames = parse_options - file_details = collect_file_stats(filenames) - total_stats = calculate_total_stats(file_details) - max_widths = calculate_max_widths(total_stats) + file_stats = collect_file_stats(filenames) + total_stat = calculate_total_stat(file_stats) + max_widths = calculate_max_widths(total_stat) - file_details.each { |file_stats| print_stats(file_stats, max_widths, options) } - print_stats(total_stats, max_widths, options) if filenames.size > 1 + file_stats << total_stat if filenames.size > 1 + file_stats.each { |file_stat| puts format_result(file_stat, max_widths, options).join(' ') } end def parse_options @@ -27,32 +27,34 @@ end def collect_file_stats(filenames) filenames.map do |filename| text = filename.empty? ? ARGF.read : File.read(filename) - { filename: filename, lines: text.lines.count, words: text.split.size, bytes: text.bytesize } + { + filename: filename, + lines: text.lines.count, + words: text.split.size, + bytes: text.bytesize + } end end -def calculate_total_stats(file_details) - total_stats = { filename: '合計', lines: 0, words: 0, bytes: 0 } - file_details.each do |stats| - total_stats[:lines] += stats[:lines] - total_stats[:words] += stats[:words] - total_stats[:bytes] += stats[:bytes] +def calculate_total_stat(file_stats) + total_stat = { filename: '合計', lines: 0, words: 0, bytes: 0 } + file_stats.each do |stats| + total_stat[:lines] += stats[:lines] + total_stat[:words] += stats[:words] + total_stat[:bytes] += stats[:bytes] end - total_stats + total_stat end -def calculate_max_widths(total_stats) - %i[lines words bytes].to_h { |key| [key, total_stats[key].to_s.length] } +def calculate_max_widths(total_stat) + %i[lines words bytes].to_h { |key| [key, total_stat[key].to_s.length] } end def format_result(stats, max_widths, options) - %i[lines words bytes].filter_map do |key| + result = %i[lines words bytes].filter_map do |key| stats[key].to_s.rjust(max_widths[key]) if options[key] end -end - -def print_stats(stats, max_widths, options) - puts (format_result(stats, max_widths, options) << stats[:filename]).join(' ') + result << stats[:filename] end main