From 40c822d7f1ca3670cb463881098a1c8a96cb7fef Mon Sep 17 00:00:00 2001 From: Rikuoh Date: Wed, 3 Jul 2024 22:17:39 +0900 Subject: [PATCH] =?UTF-8?q?=E3=81=9F=E3=81=B6=E3=82=93=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wc.rb | 38 +++++++++++++++++--------------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/wc.rb b/wc.rb index 5f902d0..c330fc2 100644 --- a/wc.rb +++ b/wc.rb @@ -8,29 +8,24 @@ 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 + opts.on('-l') { options[:lines] = true } + opts.on('-w') { options[:words] = true } + opts.on('-c') { options[:bytes] = true } end.parse! -file_path = ARGV[0] -if file_path.nil? - puts 'ファイルパスがありません。' - exit -end +input = if !ARGV.empty? + File.read(ARGV[0]) + elsif !$stdin.tty? + $stdin.read + else + puts 'ファイルパスまたはパイプラインからの入力がありません。' + exit + end -File.open(file_path) do |file| - file.each_line do |line| - lines += 1 - words += line.split.size - bytes += line.bytesize - end +input.each_line do |line| + lines += 1 + words += line.split.size + bytes += line.bytesize end options = { bytes: true, lines: true, words: true } if options.empty? @@ -39,4 +34,5 @@ result << lines if options[:lines] result << words if options[:words] result << bytes if options[:bytes] -puts "#{result.join(' ')} #{file_path}" +file_name = ARGV[0] +puts "#{result.join(' ')} #{file_name}"