Reputation: 11
I have this Hash that I use store values and if the values are not found to get default values:
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
I would like to get values based on the keys so I tried this:
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
But I get for result not number but {"AT"=>100, "BE"=>100}
. If I remove the check if payment_type.is_a?(Hash)
I get exception Integer does not have #dig method (RuntimeError)
Do you know how I can solve this issue?
Upvotes: 1
Views: 81
Reputation: 198526
payment_type
will be e.g. "AT"
- it's the argument you pass into your function, it will never be a Hash.
This rewrite should do what you want:
def amount_for(payment_type, country = nil, currency = nil)
path = [payment_type, country, currency].compact
obj = AMOUNT
obj = obj[path.shift] while Hash === obj && !path.empty?
return obj || 1
end
Alternately, this is rather similar to the code you wrote:
def amount_for(payment_type, country = nil, currency = nil)
tmp = AMOUNT.dig(payment_type, country, currency)
return tmp if tmp
tmp = AMOUNT.dig(payment_type, country)
return tmp if tmp
tmp = AMOUNT.dig(payment_type)
return tmp if tmp
return 1
end
Upvotes: 1