たぶん完成
This commit is contained in:
parent
3df439edaf
commit
0243e260b9
1 changed files with 16 additions and 16 deletions
32
wc.rb
32
wc.rb
|
@ -2,9 +2,6 @@
|
|||
|
||||
require 'optparse'
|
||||
|
||||
options, input_sources = parse_options
|
||||
input_stream_sources(input_sources, options)
|
||||
|
||||
def parse_options
|
||||
options = {}
|
||||
OptionParser.new do |opts|
|
||||
|
@ -17,8 +14,8 @@ def parse_options
|
|||
end
|
||||
|
||||
def input_stream_sources(input_sources, options)
|
||||
total_stats = [0, 0, 0]
|
||||
max_widths = [0, 0, 0]
|
||||
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)
|
||||
|
@ -40,29 +37,29 @@ def input_stream(source)
|
|||
end
|
||||
|
||||
def count_file_stats(input)
|
||||
lines = words = bytes = 0
|
||||
stats = { lines: 0, words: 0, bytes: 0 }
|
||||
input.each_line do |line|
|
||||
lines += 1
|
||||
words += line.split.size
|
||||
bytes += line.bytesize
|
||||
stats[:lines] += 1
|
||||
stats[:words] += line.split.size
|
||||
stats[:bytes] += line.bytesize
|
||||
end
|
||||
[lines, words, bytes]
|
||||
stats
|
||||
end
|
||||
|
||||
def update_totals(totals, stats)
|
||||
totals.zip(stats).map { |total, stat| total + stat }
|
||||
totals.merge(stats) { |_key, total, stat| total + stat }
|
||||
end
|
||||
|
||||
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
|
||||
|
||||
def format_result(stats, max_widths, options)
|
||||
result = []
|
||||
%i[lines words bytes].each_with_index do |key, index|
|
||||
result << stats[index].to_s.rjust(max_widths[index]) if options[key]
|
||||
result = {}
|
||||
%i[lines words bytes].each do |key|
|
||||
result[key] = stats[key].to_s.rjust(max_widths[key]) if options[key]
|
||||
end
|
||||
result.join(' ')
|
||||
result.values.join(' ')
|
||||
end
|
||||
|
||||
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)
|
||||
puts "#{total_result} 合計"
|
||||
end
|
||||
|
||||
options, input_sources = parse_options
|
||||
input_stream_sources(input_sources, options)
|
||||
|
|
Loading…
Reference in a new issue