Last active
August 8, 2023 05:52
-
-
Save orend/10135014 to your computer and use it in GitHub Desktop.
further refactoring to "Using a Ruby Class To Write Functional Code" - http://patshaughnessy.net/2014/4/8/using-a-ruby-class-to-write-functional-code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Added: Line#to_s, #parse4, #parse5 | |
class Line | |
attr_reader :Line | |
def initialize(text) | |
@line = text | |
end | |
def office | |
values[2].strip | |
end | |
def employee_id | |
values[1].strip | |
end | |
def last_name | |
name = values[0] | |
name.split[0] | |
end | |
def to_s | |
"employee_id: #{employee_id}\n" << | |
"office: #{office}\n" << | |
"last_name: #{last_name}" | |
end | |
private | |
def values | |
@values ||= @line.split(',') | |
end | |
end | |
def parse3(lines) | |
lines.map do |text| | |
Line.new(text) | |
end.each do |line| | |
puts "employee_id: #{line.employee_id}" | |
puts "office: #{line.office}" | |
puts "last_name: #{line.last_name}" | |
end | |
end | |
# Tell, don't ask | |
def parse4(lines) | |
lines.map do |text| | |
Line.new(text) | |
end.each do |line| | |
puts line.to_s | |
end | |
end | |
# A more functional approach - the input is going through a series of transformations | |
# building the entire string at once (not recommended for large collections) | |
def parse5(lines) | |
puts lines.map { |text| Line.new(text) }.join("\n") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For VERY_BIG_FILE.TXT I would do: