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

48
wc.rb
View file

@ -1,18 +1,23 @@
def wc(file_path) # frozen_string_literal: true
lines = 0
words = 0
bytes = 0
File.open(file_path) do |file| require 'optparse'
file.each_line do |line|
lines += 1 lines = 0
words += line.split.size words = 0
bytes += line.bytesize bytes = 0
end
options = {}
OptionParser.new do |opts|
opts.on('-l') do
options[:lines] = true
end end
opts.on('-w') do
[lines, words, bytes] options[:words] = true
end end
opts.on('-c') do
options[:bytes] = true
end
end.parse!
file_path = ARGV[0] file_path = ARGV[0]
if file_path.nil? if file_path.nil?
@ -20,5 +25,18 @@ if file_path.nil?
exit exit
end end
lines, words, bytes = wc(file_path) File.open(file_path) do |file|
puts "行数:#{lines}\n単語数:#{words}\nバイト数:#{bytes}\nファイルパス:#{file_path}" 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}"