开发者

A little help getting into the Ruby world?

I'm learning Ruby in my spare time and I have installed a Linux Mint 10 Virt开发者_开发知识库ual Machine on my laptop.

I've gotten most of the basic Ruby structures down and now I'd like to actually build something with it to test it out.

For my first project, I want to parse a CSV file and save the information into an array in my code.

Simple enough right?

After some Googling, I found this library that seems to be what I need to use. https://github.com/fauna/ccsv

My question is, how do I use this? I'm coming from the C#/.Net world where I would download a .dll (more recently just use NuGet) and it would be referenced into the project.

What do I need to do in Ruby? Can anyone walk me through it? I'm brand new to this language so try not to assume anything, I just may not know it yet. Thanks for your time.


I'm afraid that, in ruby, that isn't much of a project. Suppose you have a file 'test.csv' with this content

letters,numbers
a,3
b,2
d,4

You can parse it like this:

require 'csv'
data = CSV.read('test.csv')

p data
#=> [["letters", "numbers"], ["a", "3"], ["b", "2"], ["d", "4"]]

Somewhat more complicated:

data = CSV.read('test.csv',{:headers=>true})
puts data['numbers'][0] #=> 3

This {:headers=>true} looks somewhat like a block, but it is a hash. CSV takes all kinds of parameters in a hash, a common pattern.


Ruby has a default csv library, and I use a function I found at http://snippets.dzone.com/posts/show/3899 to parse the csv.

  require 'csv'
  def parse(file)
    csv_data = CSV.read file
    headers = csv_data.shift.map {|i| i.to_s }
    string_data = csv_data.map {|row| row.map {|cell| cell.to_s } }
    string_data.map {|row| Hash[*headers.zip(row).flatten] }
  end

  myHash = parse('myfile')

If you are doing ruby without OOP, the function definitions must go before the code that calls it.

To answer your initial question, you would do in the terminal:

gem install ccsv

Then in your code:

require 'ccsv'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜