たぶん完成

This commit is contained in:
Rikuoh Tsujitani 2024-07-20 22:45:14 +09:00
parent 3df439edaf
commit 0243e260b9
Signed by: riq0h
GPG key ID: 010F09DEA298C717

32
wc.rb
View file

@ -2,9 +2,6 @@
require 'optparse' require 'optparse'
options, input_sources = parse_options
input_stream_sources(input_sources, options)
def parse_options def parse_options
options = {} options = {}
OptionParser.new do |opts| OptionParser.new do |opts|
@ -17,8 +14,8 @@ def parse_options
end end
def input_stream_sources(input_sources, options) def input_stream_sources(input_sources, options)
total_stats = [0, 0, 0] total_stats = { lines: 0, words: 0, bytes: 0 }
max_widths = [0, 0, 0] max_widths = { lines: 0, words: 0, bytes: 0 }
input_sources.each do |source| input_sources.each do |source|
stats = input_stream(source) stats = input_stream(source)
@ -40,29 +37,29 @@ def input_stream(source)
end end
def count_file_stats(input) def count_file_stats(input)
lines = words = bytes = 0 stats = { lines: 0, words: 0, bytes: 0 }
input.each_line do |line| input.each_line do |line|
lines += 1 stats[:lines] += 1
words += line.split.size stats[:words] += line.split.size
bytes += line.bytesize stats[:bytes] += line.bytesize
end end
[lines, words, bytes] stats
end end
def update_totals(totals, stats) def update_totals(totals, stats)
totals.zip(stats).map { |total, stat| total + stat } totals.merge(stats) { |_key, total, stat| total + stat }
end end
def update_max_widths(max_widths, stats) def update_max_widths(max_widths, stats)
max_widths.zip(stats).map { |max, stat| [max, stat.to_s.length].max } max_widths.merge(stats) { |_key, max, stat| [max, stat.to_s.length].max }
end end
def format_result(stats, max_widths, options) def format_result(stats, max_widths, options)
result = [] result = {}
%i[lines words bytes].each_with_index do |key, index| %i[lines words bytes].each do |key|
result << stats[index].to_s.rjust(max_widths[index]) if options[key] result[key] = stats[key].to_s.rjust(max_widths[key]) if options[key]
end end
result.join(' ') result.values.join(' ')
end end
def print_result(result, source) def print_result(result, source)
@ -73,3 +70,6 @@ def print_total(total_stats, max_widths, options)
total_result = format_result(total_stats, max_widths, options) total_result = format_result(total_stats, max_widths, options)
puts "#{total_result} 合計" puts "#{total_result} 合計"
end end
options, input_sources = parse_options
input_stream_sources(input_sources, options)