如果键存在,Rails用另一个替换一个哈希



我不知道发生了什么但是我有两个哈希值:

first_hash

{
'Ids' => ['string_first_hash'],
'Description' =>
{
'Url' => 'some_path',
'EventCallback' => {
'Url' => 'some_path',
'WhiteList' => ['string'],
},
'Steps' => [{
'OrderIndex' => 1,
'Recipients' => [
{
'Email' => 'email@first.hash',
'FirstName' => 'first_hash_name',
'LastName' => 'first_hash_last_name',
'LanguageCode' => 'en',
},
],
}],
},
}

第二个:

template_hash

{
'Ids' => ['template_stirng'],
'Description' => {
'Name' => 'Template_name',
'Subject' => 'template_subject',
'Finish' => false,
'Steps' => [{
'OrderIndex' => 1,
'Recipients' => [
{
'Email' => 'Placeholder =>',
'FirstName' => '',
'LastName' => '',
'LanguageCode' => '',
'DisableEmail' => false,
'IdentificationMethods' => [],
},
],
'RecipientType' => 'Signer',
}],
},
}

现在我想将first_hash添加到template_hash并仅覆盖存在于两者中的那些键/值,并从second_hash中保留其余部分不变(应添加在结果中)。我以为我要做的就是:

test = first_hash.merge(template_hash)

但是结果是令人惊讶的-没有改变,它打印第二个哈希值不变:

> test
{"SspFileIds"=>["7fcf6021-386d-4f31-a871-a89afb8fb36e"],
"SendEnvelopeDescription"=>
{"Name"=>"1 Recipient",
"EmailSubject"=>"Please sign the enclosed envelope",
"EmailBody"=>"Dear #RecipientFirstName# #RecipientLastName#nn#PersonalMessage#nnPlease sign the envelope #EnvelopeName#nnEnvelope will expire at #ExpirationDate#",
"DisplayedEmailSender"=>"",
"EnableReminders"=>true,
"FirstReminderDayAmount"=>5,
"RecurrentReminderDayAmount"=>3,
"BeforeExpirationDayAmount"=>3,
"DaysUntilExpire"=>28,
"StatusUpdateCallbackUrl"=>"",
"LockFormFieldsAtEnvelopeFinish"=>false,
"Steps"=>
[{"OrderIndex"=>1,
"Recipients"=>
[{"Email"=>"Placeholder:",
"FirstName"=>"",
"LastName"=>"",
"LanguageCode"=>"",
"DisableEmail"=>false,
"AddAndroidAppLink"=>false,
"AddIosAppLink"=>false,
"AddWindowsAppLink"=>false,
"AllowDelegation"=>true,
"AllowAccessFinishedWorkstep"=>false,
"SkipExternalDataValidation"=>false,
"AuthenticationMethods"=>[],
"IdentificationMethods"=>[]}],
"RecipientType"=>"Signer"}]}}

怎么回事,我误会什么了吗?我使用的是Rails 7和Ruby 3。

[编辑]

expected_result

{
'Ids' => ['string_first_hash'],
'Description' => {
'Name' => 'Template_name',
'Subject' => 'template_data_string',
'Finish' => false,
'Steps' => [{
'OrderIndex' => 1,
'Recipients' => [{
'Email' => 'email@first.hash',
'FirstName' => 'first_hash_name',
'LastName' => 'first_hash_last_name',
'LanguageCode' => 'en',
}],
'RecipientType' => 'Signer',
}],
'Url' => 'some_path',
'EventCallback' => {
'Url' => 'some_path',
'WhiteList' => ['string'],
},
},
}

你试过使用deep_merge吗?https://apidock.com/rails/Hash/deep_merge

你想要的是test = first_hash.deep_merge(second_hash)

最新更新