Search code examples
ruby-on-railsrubyarrayshashpuppet

Merge a Hash and an Array in Ruby to form a Hash and add some string to the Array values to be seen in final Hash


Need to form a hash with values supplied from a User as a hash and an array ... The end hash should have the array items as keys and some extra strings added to them to make an acceptable hash that is then merged with the hash supplied initially giving preference to the array items if there happens to be a duplicate key in the hash in that

        argument1 = {
             'key1' => 'value1',
             'key2' => 'value2',
             'C'    => 'value3',
        }
        argument2 = ["X","key2","Y"]

there is need to add a key and a value string to the array items in that they are as

         X => {
             'added_string' => 'added_string2'
         }

same for key2 in the array and also Y

the above should be merged with the original argument1 to have the following output

       result => {
              'key1' => 'value1',
              'C'    => 'value3',
               'X' => {'added_string' => 'added_string2'},
               'Y' => {'added_string' => 'added_string2'},
               'key2' => {'added_string' => 'added_string2'},
       }

key2 field in the argument1 is overwritten since it is a duplicate in the argument2 array and its content set as to that of the other array items in the argument2


Solution

  • argument1 = {
      'key1' => 'value1',
      'key2' => 'value2',
      'C'    => 'value3',
    }
    argument2 = ["X","key2","Y"]
    
    added = { 'added_string' => 'added_string2' }
    
    
    puts argument1.merge(
      Hash[argument2.zip([added] * argument2.size)]
    )
    
    # Hash[:a, :b, :c, :d] => { a: :b, c: :d }
    # [:a].zip([:b]) => [[:a, :b]]
    # [:a] * 3 => [:a, :a, :a]