Skip to content

Instantly share code, notes, and snippets.

@orend
Last active August 8, 2023 05:52
Show Gist options
  • Save orend/10135014 to your computer and use it in GitHub Desktop.
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
# 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
@kml
Copy link

kml commented Apr 10, 2014

For VERY_BIG_FILE.TXT I would do:

def parse6(lines)
  lines.each do |text|
    puts Line.new(text)
  end
end

File.open('VERY_BIG_FILE.TXT') do |f|
  parse6(f)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment