提取嵌套在Ruby中的哈希数组的值

时间:2012-07-25 21:22:05

标签: ruby xml arrays hash

我从URL转换为哈希数组的XML响应,如下所示:

{
  "EmployeeList"=>{
    "EmployeeProfile"=>{
      "BuildLoc"=>{"$"=>"1 Happy Place"},
      "Status"=>{"$"=>"A"},
      "SecrTitle"=>[{}, {}],
      "ID"=>{},
      "bct"=>{},
      "NUM"=>{"$"=>"1234567"},
      "BuildCity"=>{"$"=>"Dayton"},
      "BuildFloor"=>{"$"=>"6"},
      "Expense"=>{"$"=>"1345"},
      "LastName"=>{"$"=>"Smith"},
      "Middle"=>{},
      "SecrName"=>[{}, {}],
      "InternalSMTPAddress"=>{"$"=>"Joe.Smith@happy.com"},
      "IAddress"=>{"$"=>"Joe.Smith@happy.com"},
      "PreferredLastName"=>{},
      "DisplayName"=>{"$"=>"Joe Smith"},
      "CellPhoneNo"=>{},
      "Title"=>{"$"=>"Dr."},
      "BuildStreetAddress"=>{"$"=>"123 Happy town"},
      "BuildState"=>{"$"=>"IL"},
      "FirstName"=>{"$"=>"Joe"},
      "AltContactTitle1"=>{},
      "Dept-CostCtrNo"=>{"$"=>"129923"},
      "PreferredFirstName"=>{"$"=>"Joe"},
      "AltContactName2"=>{},
      "AltContactPhone2"=>{},
      "GDP"=>{},
      "BuildZip"=>{"$"=>"112345"},
      "RegionID"=>{"$"=>"NAMR"},
      "EmploymentType"=>{"$"=>"E"},
      "TempPhone"=>{},
      "BuildID"=>{"$"=>"01114"},
      "CountryAbbr"=>{"$"=>"USA"},
      "FaxDisp1"=>{},
      "BuildCountry"=>{"$"=>"United States"}
    }
  },
  nil=>nil
}

提取“DisplayName”和“InternalSMTPAddress”值的最简单方法是什么?

3 个答案:

答案 0 :(得分:1)

如果将返回的哈希值分配给名为“hash”的变量,则可以访问这些键的两个所需值,如:

hash['EmployeeList']['EmployeeProfile']['DisplayName']
=> {"$"=>"Joe Smith"}

hash['EmployeeList']['EmployeeProfile']['InternalSMTPAddress']
=> {"$"=>"Joe.Smith@happy.com"}

如果您希望其中的实际数据添加尾随['$']

hash['EmployeeList']['EmployeeProfile']['DisplayName']['$']
=> "Joe Smith"

hash['EmployeeList']['EmployeeProfile']['InternalSMTPAddress']['$']
=> "Joe.Smith@happy.com"

答案 1 :(得分:0)

如果您需要在嵌套哈希中找到一些键,请使用以下方法:

def find_key(hash,key)
  hash.each {|k, v|
    return v if k==key
    tmp=find_key(v,key) if v.is_a?(Hash)
    return tmp unless tmp.nil?
  }
  return nil
end

用法:

hash = Hash.new
hash["key1"] = "value1"
hash["key2"] = "value2"
hash["key3"] = Hash.new
hash["key3"]["key4"] = "value4"
hash["key3"]["key5"] = "value5"
hash["key6"] = Hash.new
hash["key6"]["key7"] = "value7"
hash["key6"]["key8"] = Hash.new
hash["key6"]["key8"]["key9"] = "value9"

find_key(hash,"key9") => "value9"
find_key(hash,"key8") => {"key9"=>"value9"}
find_key(hash,"dsfsdfsd") => nil

答案 2 :(得分:0)

我建议您使用红宝石宝石nested_lookup

使用命令gem install nested_lookup

安装gem

在您的情况下,您需要'DisplayName'和'InternalSMTPAddress'的值。这是您需要做的。

Rameshs-MacBook-Pro:~ rameshrv$ irb
irb(main):001:0> require 'nested_lookup'
=> true
irb(main):051:0> include NestedLookup
=> Object
# Here the test_data is the data you gave in the question
irb(main):052:0> test_data.nested_get('DisplayName')
=> {"$"=>"Joe Smith"}
irb(main):053:0> test_data.nested_get('InternalSMTPAddress')
=> {"$"=>"Joe.Smith@happy.com"}
irb(main):054:0>

有关更多信息,请阅读https://github.com/rameshrvr/nested_lookup