【问题标题】:Return in method that called private method在调用私有方法的方法中返回
【发布时间】:2014-04-06 20:51:18
【问题描述】:

为了尝试使用更小的方法,我将方法中的某些部分移到更小的私有方法中。然而,在一个私有方法中,我正在做一些错误处理,并且想打破调用私有方法的方法,而不仅仅是私有方法本身。非常基本的示例,但是:

def public method
  private_method

  # Do other stuff based on the results of that private method
end

private

def private method
  objects = Object.where('something')
  return 'No objects' if objects.count == 0
  return 'Less than 3 objects' if objects.count < 3
  objects
end

如果是这种情况,我如何才能完全脱离公共方法并根据计数返回这些值,而不是仅仅将“无对象”返回到公共方法。

【问题讨论】:

  • 用更好的例子编辑

标签: ruby return private-methods


【解决方案1】:

这是对异常处理的一个很好的使用:

def public_method 
  begin  
    private_method 
  rescue  
    return "BlahBlah"
  end  
  # Do other stuff based on the results of that private method 
end  

private

def private_method 
  object = Object.find(1)
  raise "not found" if object.nil?
  object
end  

【讨论】:

  • 公平,但这与 def public method obj = private_method return "BlahBlah" if obj.nil? end 没有本质区别,这是我试图避免的。我将在公共方法中调用几个不同的私有方法,并且希望将所有错误处理保留在每个私有方法中,只是为了将事情保持在紧密相关的块中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多