0

I'm currently trying to write a small script which parses weekly reports(e-mails) and stores the data I want in variables, so I can handle them further.

The functionality is working already, but it's sort of hacked in at the moment and I'd like to learn how the code should look idealy.

This is my code at the moment - I shortened it a bit and made it more generic:

activated_accounts_rx = Regexp.new(/example/)
canceled_accounts_rx = Regexp.new(/example/)
converted_accounts_rx = Regexp.new(/example/)

File.open("weekly_report.txt") do |f|

    input = f.read

    activated_accounts = input.scan(activated_accounts_rx).join
    canceled_accounts = input.scan(canceled_accounts_rx).join
    converted_accounts = input.scan(converted_accounts_rx).join

end

I thought of something like this and I know that it can't work, but I don't know how I can get it to work:

var_names = ["activated_accounts", 
             "canceled_accounts", 
             "converted_accounts"]

regex = { "#{var_names[0]}": Regexp.new(/example/), 
          "#{var_names[1]}": Regexp.new(/example/) }

File.open("weekly_report.txt") do |f|

    input = f.read

    for name in var_names
        name = input.scan(regex[:#{name}]).join
    end

end

I would like to end up with variables like this:

activated_accounts = 13
canceled_accounts = 21
converted_accounts = 5

Can someone help me please?

2 Answers 2

3

You probably don't need to have a separate array for your variables. Just use them as the keys in the hash. Then you can access the values later from another hash. Better yet, if you don't need the regexes anymore, you can just replace that value with the scanned contents.

regexHash = { 
              activated_accounts: Regexp.new(/example/), 
              canceled_accounts : Regexp.new(/example/),
              converted_accounts: Regexp.new(/example/)
            }
values = {}

contents = File.open("weekly_report.txt").read
regexHash.each do |var, regex|
  values[var] = contents.scan(regex).join
end

To access your values later just use

values[:var_name] # values[:activated_accounts] for example
Sign up to request clarification or add additional context in comments.

2 Comments

I'd rename var to something like account_group and values to account_groups, but yes, this looks OK.
Oh my god, this is awesome :) Thanks a lot!!
0

If you want separate name's variable in an array, you can use to_sym:

regex = { var_names[0].to_sym => Regexp.new(/example/), 
          var_names[1].to_sym => Regexp.new(/example/) } #Rocket notation!

And:

for name in var_names
    name = input.scan(regex[var_names[0].to_sym]).join
end

Anyway, i prefer the Rob Wagner advice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.