From 65c7fc830b554e7aa367aa091eb5e2283e6ecbb6 Mon Sep 17 00:00:00 2001 From: Rikuoh Date: Tue, 2 Jul 2024 22:44:35 +0900 Subject: [PATCH] wc --- wc.rb | 48 +++++++++++++++++++++++++++++++++--------------- 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/wc.rb b/wc.rb index 7616467..5f902d0 100644 --- a/wc.rb +++ b/wc.rb @@ -1,18 +1,23 @@ -def wc(file_path) - lines = 0 - words = 0 - bytes = 0 +# frozen_string_literal: true - File.open(file_path) do |file| - file.each_line do |line| - lines += 1 - words += line.split.size - bytes += line.bytesize - end +require 'optparse' + +lines = 0 +words = 0 +bytes = 0 + +options = {} +OptionParser.new do |opts| + opts.on('-l') do + options[:lines] = true end - - [lines, words, bytes] -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? @@ -20,5 +25,18 @@ if file_path.nil? exit end -lines, words, bytes = wc(file_path) -puts "行数:#{lines}\n単語数:#{words}\nバイト数:#{bytes}\nファイルパス:#{file_path}" +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}"