fjord/wc.rb
2024-07-02 22:44:35 +09:00

42 lines
757 B
Ruby

# frozen_string_literal: true
require 'optparse'
lines = 0
words = 0
bytes = 0
options = {}
OptionParser.new do |opts|
opts.on('-l') do
options[:lines] = true
end
opts.on('-w') do
options[:words] = true
end
opts.on('-c') do
options[:bytes] = true
end
end.parse!
file_path = ARGV[0]
if file_path.nil?
puts 'ファイルパスがありません。'
exit
end
File.open(file_path) do |file|
file.each_line do |line|
lines += 1
words += line.split.size
bytes += line.bytesize
end
end
options = { bytes: true, lines: true, words: true } if options.empty?
result = []
result << lines if options[:lines]
result << words if options[:words]
result << bytes if options[:bytes]
puts "#{result.join(' ')} #{file_path}"