如果你有,你可以創建自定義函數嵌套很深的結構,以檢查是否有鍵存在,並顯示其值:
def nested_value hash, *args
tmp = hash
args.each do |arg|
return nil if tmp.nil? || !tmp.respond_to?(:[]) || (tmp.is_a?(Array) && !arg.is_a?(Integer))
tmp = tmp[arg]
end
tmp
end
例如,如果你已經從你的例子加載以下YAML:
k = [
{ "id"=>"deal one",
"options"=>{"redemptionLocations"=>[{"streetAddress1"=>"123 Any Street\""}]}},
{ "id"=>"deal two",
"options"=>[]}]
然後,你可以這樣做:
nested_value k.first, 'options', 'redemptionLocations', 0, 'streetAddress1'
=> "123 Any Street \""
nested_value k.last, 'options', 'redemptionLocations', 0, 'streetAddress1'
=> nil
謝謝大衛。我認爲,由於數據結構的深度,我得到這個錯誤:NoMethodError:未定義的方法'streetAddress1'爲零:NilClass – deadkarma 2011-03-16 17:53:49