问题几乎在标题中。重构下面的东西的最佳方法是什么?
json["data"]["counts"]["followed_by"] if json && json["data"] && json["data"]["counts"] && json["data"]["counts"]["followed_by"]
除非nil
存在,否则我想返回json["data"]["counts"]["followed_by"]
。
答案 0 :(得分:1)
您可以使用try:
json.try(:[], 'data').try(:[], 'counts').try(:[], 'followed_by')
答案 1 :(得分:1)