SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast selfmindead's Avatar
    Join Date
    Nov 2004
    Location
    Las Vegas, NV
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help reading csv data in a dynamic arrays w/ loops... =)

    Hi guys, I'm workin on a little ruby on rails application and I'm having a little trouble doing something that SHOULD be pretty easy, especially in rails... So you guys can know what I'm looking for, I included a block of PHP code that does the job, and the block of ruby code that's failing me :P. Thanks ahead of time to anyone who can help me out with this...

    - - - - -
    <?php
    $csv_file_array = functionThatSplitsFileIntoArrayByLine("somefile.csv");

    $tcount = 0;
    while ( $tcount <= count($csv_file_array) ) {
    $csv_file_array[$tcount] = explode($csv_file_array[$tcount], ",");
    $tcount++;
    }
    ?>
    - - - - -

    After this php code, $csv_file_array should be a dynamic array where i can access csv data. ($csv_file_array[1][3] = "First line, and the third value (start from zero)."


    Now, here is the code im kinda on my way to using with ruby on rails. It returns an error "index 10 out of array" so the loop's probably going on longer than it should, i just dont get how rails handles this (no 'var++' incrementing...?)

    - - - - -
    task_templates = IO.readlines("somefile.csv")

    tcount = 0
    while tcount <= task_templates.length
    task_templates.fetch(tcount).split(',')
    tcount = tcount.succ
    end
    - - - - -

    Thanks again, hope someone can help me.

  2. #2
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    data = []
    File.open("somefile.csv").each_line do |line|
    	data << line.chop.split(",")
    end

  3. #3
    eschew sesquipedalians silver trophy sweatje's Avatar
    Join Date
    Jun 2003
    Location
    Iowa, USA
    Posts
    3,749
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I did:
    Code:
    $ echo "1,2,3
    > 4,5,6" > test.csv
    for a test file.

    Then in ruby:
    Code:
     $ irb
    >> require 'csv'
    => true
    >> x =  CSV::Reader.parse(File.open('test.csv', 'rb')).collect
    => [["1", "2", "3"], ["4", "5", "6"]]
    >> p x.nitems
    2
    Jason Sweat ZCE - jsweat_php@yahoo.com
    Book: PHP Patterns
    Good Stuff: SimpleTest PHPUnit FireFox ADOdb YUI
    Detestable (adjective): software that isn't testable.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •