Reputation:
I'm new to Ruby, just learning to use it since last night. As my first task I set for myself, I'd like to load a CSV file to an array of Car objects I created.
class Car
attr_accessor :year, :make, :model, :length
def initializer(year, make, model, length)
@year = year
@make = make
@model = model
@length = length
end
def to_s
"Year: #{@year} | Make: #{@make} | Model: #{@model} | Length: #{@length}"
end
end
require 'csv'
data = CSV.read('/home/stapiagutierrez/Desktop/Pickaxe/cars.csv')
puts data[1]
How can I iterate through the data collection and load each row of values into a new Car object? Thank you for the suggestions.
Upvotes: 0
Views: 2815
Reputation: 2869
Assuming each car is on it's own line:
path = '/home/stapiagutierrez/Desktop/Pickaxe/cars.csv'
cars = CSV.read(path).collect{ |row| Car.new *row }
The *
in *row
is a "splat" operator, which tells Ruby to take an array and turn it into individual arguments. It can do the opposite and turn multiple arguments into an array, as well; see Programming Ruby on Variable-Length Argument Lists.
Upvotes: 3