如果密钥存在于MAP中,则修改参数

时间:2018-09-19 13:56:44

标签: ruby

仅当密钥存在于MAP中时,我才想修改此哈希。我尝试过:

FIXED_COUNTRY_TO_PHONE = { 
    'FI' => '+358501111',
    'RU' => '4019900780', 
    'SE' => '+4672345678',
    'UA' => '0123456789',
    'KZ' => '0123456789'  
  }.freeze


def base_params_for(payment_type)

    { payment_type:   payment_type,  
      currency:       currency,
      country:        country,
      amount:         amount_for(currency) }    

    params[:customer_phone] = FIXED_COUNTRY_TO_PHONE[country] if FIXED_COUNTRY_TO_PHONE.has_key? 'FI'
end

仅在存在密钥的情况下如何才能修改参数:customer_phone

1 个答案:

答案 0 :(得分:1)

您可以在此处使用tap

{ 
  payment_type:   payment_type,
  currency:       currency,
  country:        country,
  amount:         amount_for(currency) 
}.tap do |params|
  if FIXED_COUNTRY_TO_PHONE.has_key?(country)
    params[:customer_phone] = FIXED_COUNTRY_TO_PHONE[country] 
  end
end