Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
/test/tmp/
/test/version_tmp/
/tmp/
.idea/

# Used by dotenv library to load environment variables.
# .env
Expand Down
68 changes: 68 additions & 0 deletions 06.wc/wc.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

require 'pry'
require 'optparse'

opt = OptionParser.new
@option = {}
opt.on('-l') { |v| @option[:l] = v }
opt.parse!(ARGV)

def cal_lines_count(file)
file.lines.count
end

def cal_words_count(file)
file.split(/\s+/).size
end

def display_file_info(file)
lines_count = cal_lines_count(File.read(file))
words_count = cal_words_count(File.read(file))
bytes_count = File.size(file)

print lines_count
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

名前 行数 単語数 文字数 オプション という4つの情報を引数にとって、オプションに応じて出力するメソッドがあると、以下3箇所のコードをメソッドに集約できそうですね 👍

ぜひ検討してみてください🙏

print " #{words_count} #{bytes_count}" unless @option[:l]
print " #{file}\n"
end

def defile_file(argv)
argv.each do |file|
display_file_info(file)
end
end

def display_total(argv)
total_line = []
total_words = []
total_bytes = []

argv.each do |file|
total_line << cal_lines_count(File.read(file))
total_words << cal_words_count(File.read(file))
total_bytes << File.size(file)
end

print total_line.sum
print " #{total_words.sum} #{total_bytes.sum}" unless @option[:l]
print ' total'
end

def display_input_info(content)
line_count = cal_lines_count(content)

print line_count
print " #{cal_words_count(content)} #{content.size}" unless @option[:l]
end

def main
if ARGV.size.zero?
display_input_info($stdin.read)
else
defile_file(ARGV)
display_total(ARGV) if ARGV.size >= 2
end
end

main