Home > Software engineering >  Ruby delete specific value from hash and replace with another value
Ruby delete specific value from hash and replace with another value

Time:06-21

Is there a clear way to loop through the hash below and replace the specific value(s) with the value(s) in the 'Fills' array?

codes = ['AA', 'BB']
fills = ['FOUR', 'FIVE']

This empty hash gets populated by an 'each do' statement where is picks out the info from 'main_hash' based on the keys in the 'codes' array.

hash = {}

main_hash = {'AA' => ['1', 'TEXT', 'ONE'],
             'BB' => ['2', 'TEXT', 'TWO'],
             'CC' => ['3', 'TEXT', 'THREE']}

Ouput: I want to replace the specific value in the new 'hash' so the output looks like below:

hash = {'AA' => ['1', 'TEXT', 'FOUR'],
        'BB' => ['2', 'TEXT', 'FIVE']}

CodePudding user response:

Possible solution:

# Input
fills = ['FOUR', 'FIVE', 'SIX']

hash = {
  'AA' => ['1', 'ONE'],
  'BB' => ['2', 'TWO'],
  'CC' => ['3', 'THREE']
}
hash.transform_values { |i, _| [i, fills[i.to_i - 1]] }
# output

{
  'AA' => ['1', 'FOUR'],
  'BB' => ['2', 'FIVE'],
  'CC' => ['3', 'SIX']
}

Update:

As your incoming data is changed the solution will be:

h = {"AA"=>["1", "FOUR"], "BB"=>["2", "FIVE"]}

h.transform_values { |x| x.insert(1, 'TEXT') }
# Output

{
  'AA' => ['1', 'TEXT', 'FOUR'], 
  'BB' => ['2', 'TEXT', 'FIVE']
}
  • Related