How to merge the hash this way

Rajago

New Member
#1
I have written a huge code something like below
Mã:
 headers, *data_rows = @testCaseSheet
    local = headers.zip(*data_rows)
    local = local[1..-1].map {|dataRow| local[0].zip(dataRow).to_h}
    testCaseHash = {}
    local.each do |value|
      testCaseHash[value["Locator"]] = value.tap {|hs| hs.delete("Locator")}
    end
    @testCaseSheet = []
    p testCaseHash
    [h["Test Name"], testCaseHash],
which output me this as below, now I need to merge this action with each test, I don't know how to do this.
Mã:
hash= {"Action"=>{"css=#entityType"=>"Type", "id=idNumber"=>"TypeAndWait", "id=shortName"=>"TypeAndTab", "id=FirstName"=>"TypeTabAndWait", nil=>nil},

"Test1"=>{"css=#entityType"=>"Individual", "id=idNumber"=>"2323", "id=shortName"=>"M", "id=FirstName"=>"Abc", "id=lastName"=>"Gg"},

"Test2"=>{"css=#entityType"=>"Legal", "id=idNumber"=>"2323", "id=shortName"=>"Z", "id=FirstName"=>"Xyz", "id=lastName"=>"Gg"}}
Now I want to merge this action with the followings tests for an example,
Mã:
hash= { "Test1"=>{"css=#entityType"=>["Individual","Type"], "id=idNumber"=>["2323","TypeAndWait"], "id=shortName"=>["M","TypeAndTab"], "id=FirstName"=>["Abc","TypeTabAndWait"]},

"Test2"=>{"css=#entityType"=>["Legal""Type"], "id=idNumber"=>["2323","TypeAndWait"], "id=shortName"=>["Z","TypeAndTab"], "id=FirstName"=>["Xyz","TypeTabAndWait"]}}
I don't know how to merge this way, Can anyone help me?
 

Admin

Administrator
Thành viên BQT
#2
If I understand you want something like this
Mã:
hash_1 = {a: "a1", b: "b1", c: "c1"}
hash_2 = {a: "a2", b: "b2", d: "d1"}

p hash_1.merge(hash_2) { |k, v1, v2| v1 = [v1, v2] }
# => {:a=>["a1", "a2"], :b=>["b1", "b2"], :c=>"c1", :d=>"d1"}
Which in your case can be:
Mã:
test_1_value = my_hash['Test1'].merge(my_hash['Action']) { |k, v1, v2| v1 = [v1, v2] }

# => {"css=#entityType"=>["Individual", "Type"], "id=idNumber"=>["2323", "TypeAndWait"], "id=shortName"=>["M", "TypeAndTab"], "id=FirstName"=>["Abc", "TypeTabAndWait"], "id=\"lastName"=>"Gg", nil=>nil}
This is a general solution, you can manipulate furthermore removing the unwanted keys ad apply to fit your needs.

Edit - picking up comments
Remove unwanted keys and simplified merge block:
Mã:
keys_to_remove = ["id=lastName", "whatever", nil]
test_1_value = my_hash['Test1'].merge(my_hash['Action']) { |k, *vs| vs }.delete_if{ |k, _| keys_to_remove.include? k }
# => {"css=#entityType"=>["Individual", "Type"], "id=idNumber"=>["2323", "TypeAndWait"], "id=shortName"=>["M", "TypeAndTab"], "id=FirstName"=>["Abc", "TypeTabAndWait"]}
 
OP
OP
R

Rajago

New Member
#3
Hi, thats perfect , I wrongly given the "id="last name" instead of "id=last name" as key and this key is not in action so this should not come in result .
 
Top