Wierd problem reading fields in a tab-delimitted row...

Discussion in 'Ruby' started by Kurt Euler, Aug 24, 2003.

  1. Kurt Euler

    Kurt Euler Guest

    Everyone--

    A wierd problem occurs in Ruby 1.67, 1.68 and 1.8 (and probably other versions?): If I step through rows in a tab-delimited text file using code like this:

    IO.foreach("wierd.txt") { |x|
    field = x.chop.split("\t")
    if field[4] != ""
    puts "some_string"
    puts field[4]
    else
    puts "no_string"
    puts field[4]
    end
    }

    to read each line of a text file (wierd.txt) as in this example:

    string1<tab>string2<tab>string3<tab><tab><tab><tab>string4<tab><tab>
    string4<tab>string5<tab>string6<tab><tab><tab><tab>string8<tab>
    string9<tab>string10<tab>string11<tab><tab><tab><tab>
    string12<tab>string13<tab>string14<tab><tab><tab><tab>string15


    I get this output:

    ===================
    no_string

    no_string

    some_string
    nil
    no_string
    ===================

    The question is, why does field[4] only get assigned nil in the 3rd line but some phantom non-"nil" value in the 1st, 2nd, and 4th lines? The general case I've found is that a nil value is read from a 'column' if there are no strings in any 'columns' to the right.

    Thanks if you can help!

    -Kurt
    Kurt Euler, Aug 24, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Naren
    Replies:
    0
    Views:
    367
    Naren
    May 11, 2004
  2. sfp
    Replies:
    1
    Views:
    476
    mrcakey \(The Eclectic Electric\)
    Feb 5, 2007
  3. Lionel
    Replies:
    22
    Views:
    631
    Steve Holden
    Feb 3, 2009
  4. D
    Replies:
    0
    Views:
    197
  5. AMT2K5
    Replies:
    1
    Views:
    179
    Eric Schwartz
    Nov 8, 2005
Loading...

Share This Page