2011-03-16 91 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 
相关问题