从Ruby Hash获取修复值

时间:2017-11-24 08:28:11

标签: ruby

我有值response_data存储这些数据:

{"response_data"=>
  {"transaction_type"=>"void",
   "status"=>"error",
   "unique_id"=>"ec8b1e786efe64f667ad19ff1b39fb92",
   "transaction_id"=>"kcyplptlpk966yifmuct6jj0od",
   "code"=>"410",
   "technical_message"=>"no approved reference transaction found",
   "message"=>"Something went wrong, please contact support!",
   "mode"=>"test",
   "timestamp"=>"2017-11-24T08:07:40Z",
   "descriptor"=>"rwgwg",
   "sent_to_acquirer"=>"false"}}

我如何获得状态代码键?如果找不到它们会引发错误信息。

3 个答案:

答案 0 :(得分:1)

您可以使用default_proc

  

设置要在每次失败的键查找时执行的默认过程。

class CustomError < StandardError; end

response_data = {
  "transaction_type" => "void",
  # "status" => "error",
  "unique_id" => "ec8b1e786efe64f667ad19ff1b39fb92",
  "transaction_id" => "kcyplptlpk966yifmuct6jj0od",
  # "code" => "410",
  "technical_message" => "no approved reference transaction found",
  "message" => "Something went wrong, please contact support!",
  "mode" => "test",
  "timestamp" => "2017-11-24T08:07:40Z",
  "descriptor" => "rwgwg",
  "sent_to_acquirer" => "false"
}

response_data.default_proc = proc do |hash, key|
  raise CustomError.new('Message') if key.eql?('code') || key.eql?('status')
end

data = {
  'response_data' => response_data
}

data['response_data']['code'] # Custom error will be raised if code is not present
data['response_data']['status'] # Custom error will be raised if status is not present

答案 1 :(得分:0)

因此,如果我理解正确,您可以检查codestatus是否都为零,然后引发错误。

data = {"response_data"=>
    {"transaction_type"=>"void",
    "status"=>"error",
    "unique_id"=>"ec8b1e786efe64f667ad19ff1b39fb92",
    "transaction_id"=>"kcyplptlpk966yifmuct6jj0od",
    "code"=>"410",
    "technical_message"=>"no approved reference transaction found",
    "message"=>"Something went wrong, please contact support!",
    "mode"=>"test",
    "timestamp"=>"2017-11-24T08:07:40Z",
    descriptor"=>"rwgwg",
    "sent_to_acquirer"=>"false"}}
if data['response_data']['status'].nil? && data['response_data']['code'].nil?
    raise 'Error and code are not found' 
end

答案 2 :(得分:0)

另一种方式......

status = data["response_data"]["status"] or raise "missing status"
code   = data["response_data"]["code"]   or raise "missing code"