How do you read text file by creating a Hash in a script?

Discussion in 'Ruby' started by Mmcolli00 Mom, Dec 2, 2008.

  1. This is some example contents of my text file: logzT09.txt

    00834 tue z0sdf
    01230 wed z0sdf
    34234 tue wet0f

    How can I read this in another ruby script by using an Hash? I am
    wanting to use certain lines/words to compare in another ruby script so
    I need to be able to reference each word when needed. I am a beginner.
    Please help if you can. Thanks. MC
    --
    Posted via http://www.ruby-forum.com/.
     
    Mmcolli00 Mom, Dec 2, 2008
    #1
    1. Advertising

  2. Mmcolli00 Mom wrote:
    > This is some example contents of my text file: logzT09.txt
    >
    > 00834 tue z0sdf
    > 01230 wed z0sdf
    > 34234 tue wet0f
    >
    > How can I read this in another ruby script by using an Hash?


    Do you mean, how to read it into a Hash? Just read the file one line at
    a time, splitting it into key and value as you desire, and then add that
    as a new element into the Hash.

    Methods you may find useful:

    File.open
    each_line (for an IO object, yields a string for each line)
    chomp (for a String object, chop off the final newline)
    split (for a String object, split by default on spaces)

    Hash methods:

    h = {} # create an empty Hash
    h = Hash.new # an alternative way of doing the same thing
    h[key] = value # create or overwrite an entry in the Hash
    --
    Posted via http://www.ruby-forum.com/.
     
    Brian Candler, Dec 2, 2008
    #2
    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. bthumber
    Replies:
    0
    Views:
    375
    bthumber
    Jul 6, 2010
  2. rp
    Replies:
    1
    Views:
    534
    red floyd
    Nov 10, 2011
  3. Srijayanth Sridhar
    Replies:
    19
    Views:
    624
    David A. Black
    Jul 2, 2008
  4. Mmcolli00 Mom
    Replies:
    2
    Views:
    197
    Mmcolli00 Mom
    Jan 27, 2009
  5. Replies:
    14
    Views:
    187
    C.DeRykus
    Dec 22, 2009
Loading...

Share This Page