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

M

Mmcolli00 Mom

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
 
B

Brian Candler

Mmcolli00 said:
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,999
Latest member
MakersCBDGummiesReview

Latest Threads

Top