vendredi 23 mars 2018

How to add new key-value pair in a Ruby Hash?

I've a hash called new_array which I've filled with key-value pairs received from a web hook notification. When that is done, I tried to enter a new key-value pair in the same hash called new_array. The problem is when I loop through the hash I've created, I only see the latest key-value pair I filled in the second step. Those I got from the webhook are all gone. This indicates that the key-value pair I entered later has overridden the old key-value pairs.

My goal in this case is to have all the key-value pairs in the hash new_array.

I also tried to create 2 individual hashes called new_array, new_array1 and merge them together like new_array.merge!(new_array1). That produced the same result. I hope someone can point me out the mistake I am making. The full code is below.

def test_method
      new_array = Hash.new
      @webhook[:note_attributes].each do |attribute|
         new_array[attribute[:name]] = attribute[:value]
      end

      if @webhook['source_name'] == 'shopify_draft_order'
         @gbp_rate = 1.41
         new_array["exchange_rate_gbp"] = @gbp_rate
      end

      new_array.each do |x|
         logger.debug "****************#{x}*****************"
      end

      new_array.to_json
   end

Aucun commentaire:

Enregistrer un commentaire