Newb: Rake - Read file and correctly save on DB

Hi all,

I’m working on a quite big project in Rails and I love the language, though I’m not an expert programmer.

I’m facing a problem that I apparently can’t overcome.

It’s a backend task (rake) which reads an input file, like this:

01aaaaa
01bbbbb
02ccccc
02ddddd

First two digit are record types (01, 02). The first 01 record type should be matched with the first 02 record type and so on.

Record types that should be matched also have a unique id in the string:

(01aaaaa-key1 => 02ccccc-key1).

My code at the moment is this, and it’s placed inside a transaction do block as all validations must be performed before the commit:

record[:01].each_with_index do |re, i|
    record_attr = {:mainrecord_id => nil,
                    :surname => var1,
                    :name => var2,
                    :birthdate => var3,
                    }
        if record[:02].each_with_index do |rc, i|
            record_attr = {
                            :country => var4
                            :city => var5
                            :street => var6
            }.merge(record_attr)
        end
        end
    full_record = Record.new(record_attr)
    db.save << full_record
end

Record type 01 is written correctly on the DB; however, with the second each_with_index do block, the additional attributes of the record[:02] are the same in every row (always the first 02 record in every row).

Can you please suggest a way on how to match the first 01 record with the first 02 record (always coupled)?

Is it necessary to write additional code in order to use the unique key or can it be accomplished with iteration only?

Is there a specific method to pair values in ruby eventually?

Thank you in advance for your support.

Regards, Moris.

It looks like the solution is simpler than I thought.
My solution is to add a second if in order to merge the hash only when the condition is met:

record[:01].each_with_index do |re, i|
    record_attr = {:mainrecord_id => nil,
                    :surname => var1,
                    :name => var2,
                    :birthdate => var3,
                    }
        if record[:02].each_with_index do |rc, I|
             if record[:02]<key1> == record[:01]<key1>`
            record_attr = {
                            :country => var4
                            :city => var5
                            :street => var6
            }.merge(record_attr)
              end
        end
        end
    full_record = Record.new(record_attr)
    db.save << full_record
end