【问题标题】:Rails: Refactoring - json["data"]["counts"]["followed_by"] if json && json["data"] && json["data"]["counts"] && json["data"]["counts"]["followed_by"] [duplicate]Rails:重构 - json["data"]["counts"]["followed_by"] if json && json["data"] && json["data"]["counts"] && json["data"]["计数"]["followed_by"] [重复]
【发布时间】:2015-09-26 21:46:44
【问题描述】:

问题几乎在标题中。重构以下内容的最佳方法是什么?

json["data"]["counts"]["followed_by"] if json &&  json["data"] && json["data"]["counts"] && json["data"]["counts"]["followed_by"]

除非json["data"]["counts"]["followed_by"] 存在,否则我想返回nil

【问题讨论】:

    标签: ruby-on-rails refactoring


    【解决方案1】:

    您可以使用try

    json.try(:[], 'data').try(:[], 'counts').try(:[], 'followed_by')
    

    【讨论】:

      【解决方案2】:

      我倾向于使用andand gem 较长的try 链,例如,

       json.andand['data'].andand['counts'].andand['followed_by']
      

      IMO 它只是看起来更好。

      【讨论】:

      • andand gem 1 分。它绝对比使用长 try 链看起来更好。
      猜你喜欢
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-13
      • 2016-12-18
      • 2015-12-27
      相关资源
      最近更新 更多