2011-03-16 86 views
1

我正在開發一個Rails應用程序,它從Groupon的API中提取數據並將其顯示在我們的網站上。在Rails中處理不存在變量的最佳方式是什麼?

採取後續的數據結構,例如:

 
--- 
- "id": deal one 
    "options": 
    "redemptionLocations": 
    - "streetAddress1": 123 Any Street" 

- "id": deal two 
    "options": [] 

如果我想遍歷各個交易,並顯示streetAddress1如果存在的話,什麼是應該做的是在Rails的最佳方法是什麼?

回答

0

只要做到:

if(defined? streetAddress1) then 
    print streetAddress1 + " is set" 
end 

希望它可以幫助

0

最好的做法應該是用present?:僅在

puts "It is #{object.attribute}" if object.attribute.present? 

如果你有對象的數組,並希望環那些有屬性設置的,可以使用select

array.select{|object| object.attribute.present?}.each do |object| 
    ... 
end 
+0

謝謝大衛。我認爲,由於數據結構的深度,我得到這個錯誤:NoMethodError:未定義的方法'streetAddress1'爲零:NilClass – deadkarma 2011-03-16 17:53:49

0

如果你有,你可以創建自定義函數嵌套很深的結構,以檢查是否有鍵存在,並顯示其值:

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 
相關問題