Ruby 在调用私有方法的方法中返回
为了尝试使用更小的方法,我将方法中的一些部分移动到更小的私有方法中。然而,在一个私有方法中,我正在进行一些错误处理,并希望突破调用私有方法的方法,而不仅仅是私有方法本身。非常基本的示例,但是:Ruby 在调用私有方法的方法中返回,ruby,return,private-methods,Ruby,Return,Private Methods,为了尝试使用更小的方法,我将方法中的一些部分移动到更小的私有方法中。然而,在一个私有方法中,我正在进行一些错误处理,并希望突破调用私有方法的方法,而不仅仅是私有方法本身。非常基本的示例,但是: def public method private_method # Do other stuff based on the results of that private method end private def private method objects = Object.wh
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
如果是这样的话,我如何完全脱离public方法并根据计数返回这些值,而不是只向public方法返回“No objects”。这是异常处理的一个很好的用法:
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返回BlahBlah if obj.nil没有本质区别?结束,这正是我想要避免的。我将在public方法中调用两个不同的私有方法,并希望在每个私有方法中保留所有错误处理,只是为了将内容保持在紧密的、相关的块中