0

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.

2
  • 2
    That should be def initialize, no "r". Commented Feb 16, 2011 at 20:47
  • @echoback: Hehe good catch! Still getting to grips with this beautiful language. Commented Feb 16, 2011 at 20:49

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

When using your code, I get this error: AccountingSystem.rb:20: syntax error, unexpected tSTAR, expecting kEND cars << Car.new *row ^ AccountingSystem.rb:24: syntax error, unexpected $end, expecting kEND puts data[1] ^
Works for me on 1.9.2-p0 and 1.8.7-p330. Which version are you using?
Thanks, harbichidian, for completing this great example of processing a CSV file; but can you show what the syntax would be for iterating over each line, i.e. doing some processing on each line in a loop? This compact Ruby syntax is rather cryptic...elegant, but cryptic...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.