从嵌套哈希中获取值

时间:2019-05-28 11:16:54

标签: ruby

我有此哈希,我使用商店值,如果未找到这些值以获取默认值:

AMOUNT = {
  EUR: {
    eps:         { AT: 1_00 },
    safetypay:   { PE: 15_000_00, CR: 5_000_00, BE: 15_000_00, },
    przelewy24:  5_00,
    qiwi:        5_00,
    bcmc:        { AT: 1_00, BE: 1_00 },
    giropay:     { DE: 1_00 },
    ideal:       { NL: 1_00 },
    mybank:      { IT: 1_00, FR: 1_00 },
  },
  CZK: {
    trustpay:   { CZ: 20_00 }
  }
}.with_indifferent_access

我想基于键获取值,所以我尝试了这一点:

def amount_for(payment_type, country, currency)
  payment_amount = AMOUNT.dig(currency, payment_type, country) if payment_type.is_a?(Hash)
  payment_amount ||= AMOUNT.dig(currency, payment_type)
  payment_amount ||= 1
end

但是我得到的结果不是数字而是{"AT"=>100, "BE"=>100}。如果我删除支票if payment_type.is_a?(Hash),则会得到异常Integer does not have #dig method (RuntimeError)

您知道我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

payment_type将例如"AT"-这是您传递给函数的参数,永远不会是哈希。

您希望AMOUNT[payment_type]成为Hash,而不是payment_type