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}"