从地图获取值

问题描述 投票:-4回答:1

我有这个哈希:

PAYMENT_TYPE_TO_CURRENCY_AND_COUNTRY_MAPPING = {
  zimpler: {'EUR' => ['FI'], 'SEK' => ['SE']},
  qiwi: {'EUR' => ['RU', 'KZ'], 'RUB' => ['RU'], 'KZT' => ['KZ'], 'USD' => ['UA']},
  payu: {'CZK' => ['CZ'], 'PLN' => ['PL']},
  entercash: {'EUR' => ['AT', 'DE', 'FI'], 'SEK' => ['SE']},
  davivienda: {'USD' => ['CO']},
  banco_de_chile: {'USD' => ['CL']}
}

我想要使​​用sample从结构中随机货币和国家。我做了:

currency = PAYMENT_TYPE_TO_CURRENCY_TO_COUNTRY_BY_PAYMENT_TYPE_MAPPING[payment_type].keys.sample
country = PAYMENT_TYPE_TO_CURRENCY_TO_COUNTRY_BY_PAYMENT_TYPE_MAPPING[payment_type][currency].sample

我明白了:

undefined method `keys' for nil:NilClass (RuntimeError)

我该如何实现呢?

ruby hash
1个回答
1
投票

看起来你正在使用一个不存在的变量?你的结构被称为PAYMENT_TYPE_TO_CURRENCY_AND_COUNTRY_MAPPING,但你在PAYMENT_TYPE_TO_CURRENCY_TO_COUNTRY_BY_PAYMENT_TYPE_MAPPING上采样。

我尝试了相同的代码,但使用了包含您的结构的相同变量,它适用于我:

PAYMENT_TYPE_TO_CURRENCY_AND_COUNTRY_MAPPING = {
  zimpler: {'EUR' => ['FI'], 'SEK' => ['SE']},
  qiwi: {'EUR' => ['RU', 'KZ'], 'RUB' => ['RU'], 'KZT' => ['KZ'], 'USD' => ['UA']},
  payu: {'CZK' => ['CZ'], 'PLN' => ['PL']},
  entercash: {'EUR' => ['AT', 'DE', 'FI'], 'SEK' => ['SE']},
  davivienda: {'USD' => ['CO']},
  banco_de_chile: {'USD' => ['CL']}
}

payment_type = :qiwi

currency = PAYMENT_TYPE_TO_CURRENCY_AND_COUNTRY_MAPPING[payment_type].keys.sample
country = PAYMENT_TYPE_TO_CURRENCY_AND_COUNTRY_MAPPING[payment_type][currency].sample
© www.soinside.com 2019 - 2024. All rights reserved.