Skip to content

Instantly share code, notes, and snippets.

@LewisYoul
Last active February 9, 2019 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LewisYoul/10afb1eda08545ae7a3cadaf55dd21ad to your computer and use it in GitHub Desktop.
Save LewisYoul/10afb1eda08545ae7a3cadaf55dd21ad to your computer and use it in GitHub Desktop.
# './people.csv' file contents
#
# name,age,hometown
# Tina,22,London
# Jim,32,Manchester
# Harriet,41,Swansea
# declare the Person class in ./person.rb
class Person
def initialize(args)
@name = args['name']
@age = args['age'].to_i
@hometown = args['hometown']
end
def summarize
puts "#{name} is #{age} years old and lives in #{hometown}."
end
private
attr_reader :name, :age, :hometown
end
# csv-parser.rb
# Read the csv file and instantiate new People, then print a summary about each one
require 'csv'
require_relative './person.rb'
csv = CSV.read('people.csv', headers: true)
people = csv.map { |person| Person.new(person.to_h) }
people.map(&:summarize)
#prints
# Tina is 22 years old and lives in London.
# Jim is 32 years old and lives in Manchester.
# Harriet is 41 years old and lives in Swansea.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment