CSV objects in Ruby. What are they exactly?

141 Views Asked by At

So I have this piece of code:

data = CSV.open(filename, headers: true, header_converters: :symbol)
    @contents = data.map

filename is the path to the file and refers to an actual file on my computer.

My question is what exactly is the CSV object that I named data? How does one map through an object?

When I debug using pry, I see this:

[1] pry(#<Session>)> data  

=> <#CSV io_type:File io_path:"./data/event_attendees.csv" encoding:UTF-8 lineno:2 col_sep:"," row_sep:"\n" quote_char:"\"" headers:[:_, :regdate, :first_name, :last_name, :email_address, :homephone, :street, :city, :state, :zipcode]>  

[2] pry(#<Session>)> row 

CSV::Row _:"1" regdate:"11/12/08 10:47" first_name:"Allison" last_name:"Nguyen" email_address:"[email protected]" homephone:"6154385000" street:"3155 19th St NW" city:"Washington" state:"DC" zipcode:"20010"

So data seems to refer to a CSV object and not an array. row seems to refer to certain attributes of the csv object?

Either way, I haven't ever seen the method map on an object before. What is going on?

1

There are 1 best solutions below

0
On

map works on any object that includes the Enumerable mixin. In order to work with Enumerable, the class needs to provide each - that's the foundation all the other nice methods are built on. Objects of the CSV class fit this pattern, as you can see in the documentation for the class.

(The reason it doesn't push it straight into an array is because it's nice to be able to read the input file line by line rather than having to store the whole thing in memory before doing anything with it.)