Ruby: Interpolate strings in hash creation

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?

Upvotes: 0

Views: 111

Answers (2)

Madh
Madh

Reputation: 131

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.

Upvotes: 0

Rob Wagner
Rob Wagner

Reputation: 4421

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

Upvotes: 3

Related Questions