This commit is contained in:
Rikuoh Tsujitani 2024-07-02 22:44:35 +09:00
parent eeb2006675
commit 65c7fc830b
Signed by: riq0h
GPG key ID: 010F09DEA298C717

40
wc.rb
View file

@ -1,8 +1,30 @@
def wc(file_path)
# 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
@ -11,14 +33,10 @@ def wc(file_path)
end
end
[lines, words, bytes]
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]
file_path = ARGV[0]
if file_path.nil?
puts 'ファイルパスがありません。'
exit
end
lines, words, bytes = wc(file_path)
puts "行数:#{lines}\n単語数:#{words}\nバイト数:#{bytes}\nファイルパス:#{file_path}"
puts "#{result.join(' ')} #{file_path}"