完成したと思いたい
This commit is contained in:
parent
16e5867588
commit
4e86d315e1
1 changed files with 15 additions and 19 deletions
32
wc.rb
32
wc.rb
|
@ -4,11 +4,12 @@ require 'optparse'
|
|||
|
||||
def main
|
||||
options, filenames = parse_options
|
||||
file_stats = collect_file_stats(filenames)
|
||||
total_stats = calculate_total_stats(file_stats)
|
||||
file_details = collect_file_stats(filenames)
|
||||
total_stats = calculate_total_stats(file_details)
|
||||
max_widths = calculate_max_widths(total_stats)
|
||||
print_file_stats(file_stats, max_widths, options)
|
||||
print_file_stats([total_stats], max_widths, options) if filenames.size > 1
|
||||
|
||||
file_details.each { |file_stats| print_stats(file_stats, max_widths, options) }
|
||||
print_stats(total_stats, max_widths, options) if filenames.size > 1
|
||||
end
|
||||
|
||||
def parse_options
|
||||
|
@ -25,14 +26,14 @@ end
|
|||
|
||||
def collect_file_stats(filenames)
|
||||
filenames.map do |filename|
|
||||
input = filename.empty? ? ARGF.read : File.read(filename)
|
||||
{ filenames: filename, lines: input.lines.count, words: input.split.size, bytes: input.bytesize }
|
||||
text = filename.empty? ? ARGF.read : File.read(filename)
|
||||
{ filename: filename, lines: text.lines.count, words: text.split.size, bytes: text.bytesize }
|
||||
end
|
||||
end
|
||||
|
||||
def calculate_total_stats(file_stats)
|
||||
total_stats = { filenames: '合計', lines: 0, words: 0, bytes: 0 }
|
||||
file_stats.each do |stats|
|
||||
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]
|
||||
|
@ -41,22 +42,17 @@ def calculate_total_stats(file_stats)
|
|||
end
|
||||
|
||||
def calculate_max_widths(total_stats)
|
||||
%i[lines words bytes].each_with_object({}) do |key, max_widths|
|
||||
max_widths[key] = total_stats[key].to_s.length
|
||||
end
|
||||
%i[lines words bytes].to_h { |key| [key, total_stats[key].to_s.length] }
|
||||
end
|
||||
|
||||
def format_result(stats, max_widths, options)
|
||||
%i[lines words bytes].filter_map do |key|
|
||||
stats[key].to_s.rjust(max_widths[key]) if options[key]
|
||||
end.join(' ')
|
||||
end
|
||||
end
|
||||
|
||||
def print_file_stats(file_stats, max_widths, options)
|
||||
file_stats.each do |stats|
|
||||
result = format_result(stats, max_widths, options)
|
||||
puts [result, stats[:filenames]].join(' ')
|
||||
end
|
||||
def print_stats(stats, max_widths, options)
|
||||
puts (format_result(stats, max_widths, options) << stats[:filename]).join(' ')
|
||||
end
|
||||
|
||||
main
|
||||
|
|
Loading…
Reference in a new issue