首页 > 解决方案 > 如果 MAP 中存在密钥,则修改参数

问题描述

仅当 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仅当密钥存在时,我如何才能修改参数?

标签: ruby

解决方案


你可以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

推荐阅读