Tony Vincent Tony Vincent - 7 months ago 16
Ruby Question

Map array elements to hash values Ruby

I have a hash here,

@property_hash = {
:code => '',
:fname => '',
:lname => '',
:basic_sal => '',
:emp_type => '',
}


and an array

line = [02,'Firstname', 'LastName', 5800, 'PL']


I want to map the array into the hash like

@property_hash = {
:code => 02,
:fname => 'Firstname',
:lname => 'LastName',
:basic_sal => 5800,
:emp_type => 'PL',
}


what is the best way to do this ??
Thank you

Answer

My solution assumes that line has the same order every time. So I define another array with the field names, merge the corresponding array elements together and convert the result into a hash.

line = [02, 'Firstname', 'LastName', 5800, 'PL']
fields = [:code, :fname, :lname, :basic_sal, :emp_type]    


key_value_pairs = fields.zip(line)
# => [[:code, 2], [:fname, "Firstname"], [:lname, "LastName"], [:basic_sal, 5800], [:emp_type, "PL"]]

@property_hash = Hash[key_value_pairs]
# => {:code=>2, :fname=>"Firstname", :lname=>"LastName", :basic_sal=>5800, :emp_type=>"PL"}
Comments