0

I'm trying to go through a file line-by-line and, if that line contains the hash key, I want to print the value. For example:

Months = { "January" => 1, "February" => 2, "March" => 3 } 

and if I have a file that contains:

February January March 

I want the output to be:

2 1 3 

Can anyone give me some quick advice?

2 Answers 2

2

Assuming the following data structure:

data = 'Months = { "January" => 1, "February" => 2, "March" => 3 }' 

This will scan through it to find the numbers associated with the month names:

months_to_find = %w[January February March] months_re = Regexp.new( '(%s) .+ => \s+ (\d+)' % months_to_find.join('|'), Regexp::IGNORECASE | Regexp::EXTENDED ) Hash[*data.scan(months_re).flatten]['January'] # => 1 

The magic occurs here:

months_re = Regexp.new( '(%s) .+ => \s+ (\d+)' % months_to_find.join('|'), Regexp::IGNORECASE | Regexp::EXTENDED ) 

which creates this regex:

/(January|February|March) .+ => \s+ (\d+)/ix 

Add additional months to months_to_find.

That will continue to work if the data is changed to:

data = 'Months = { "The month is January" => 1, "The month is February" => 2, "The month is March" => 3 }' 
Sign up to request clarification or add additional context in comments.

Comments

1
months = { "January" => 1, "February" => 2, "March" => 3 } File.open('yourfile.txt').each_line do |line| result = months[line.strip] puts result if result end 

3 Comments

ah ha. Thank you for that. Something i forgot to mention is that my line has multiple characters on it. Is there a quick fix i code do with the above code to fix that? For example if the line contained " the month is February the month is January the month is March " each on different lines
@JaronBradley, the comment doesn't make sense. What does "my line has multiple characters on it" mean? We need to see examples in your question showing the various ways your data could appear.
@JaronBradley, not certainly sure about your data file, but here is some possible fix pastie.org/4403285

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.