1

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']}

1 Answer 1

1

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']
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I did manage to get it working but made a slight change. If you look at the code now whenever I try your solution I get the following: {"AA"=>["1", "FOUR"], "BB"=>["2", "FIVE"]}. I want to display hash = {'AA' => ['1', 'TEXT', 'FOUR'], 'BB' => ['2', 'TEXT', 'FIVE']} as the output. Thanks.
You provided totally new values
Yeah sorry, I should have made it clear the first time.
You need to update you question not completely change it. I updated my answer

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.