Ruby 简化'if-then'块
我有几个代码实例如下所示:Ruby 简化'if-then'块,ruby,Ruby,我有几个代码实例如下所示: if checkProperties(top_properties, payload) == false return false end checkProperties只有一个返回值用于false,具体取决于某些条件: def checkProperties(properties, to_check) properties.each do |property| if to_check[property.to_s].nil? or to_ch
if checkProperties(top_properties, payload) == false
return false
end
checkProperties
只有一个返回值用于false
,具体取决于某些条件:
def checkProperties(properties, to_check)
properties.each do |property|
if to_check[property.to_s].nil? or to_check[property.to_s].blank?
log_err("Something went wrong")
return false
end
end
end
不过,我觉得这可以简化。仅使用以下内容是否有效
return false unless checkProperties(top_properties, payload)
任何其他建议?您可以向
all?
枚举器查询。仅当all具有以下值时,才会返回true:
def checkProperties(properties, to_check)
properties.all? { |p| to_check[p.to_s] && !to_check[p.to_s].blank? }
end
如果要检查的
中的任何属性为nil/不存在,all?
将返回false并从此处停止迭代。首先不要从块返回。改为使用break
:
def checkProperties(properties, to_check)
properties.each_with_object(true) do |property, _|
if to_check[property.to_s].to_s.empty?
log_err("Something went wrong")
break false
end
end
end
或者使用any?
和/或all?
:
def checkProperties(properties, to_check)
(!properties.any? { |p| to_check[p.to_s].to_s.empty? }).tap do |good|
log_err("Something went wrong") unless good
end
end
要显式显示缺少的属性,请使用:
我还自由地重命名了一个方法,以遵循Ruby命名约定(对于返回true
/false
的方法,在末尾有一个问号的snake case)
需要使用双关技巧从find
返回的可能值中生成true
/false
:缺少的属性或nil
还有其他建议吗
自定义错误类将起作用:
class PropertyError < StandardError
end
这将消除对条件和显式返回的需要,您只需调用:
def foo
check_properties(top_properties, payload)
# do something with top_properties / payload
end
在“上面”的某个地方,您可以处理日志记录:
begin
foo
rescue PropertyError
log_err 'Something went wrong'
end
当然,您也可以将缺少的属性的名称或其他信息存储在异常中,以提供更有意义的错误/日志消息。首先没有方法blank?
。它是rails,#blank?
包括检查nil
。另外,请从标题中删除“trialent”;这个问题没有提到三元(条件?truthy:false
)if
/的缩写形式,除非
被称为“后缀符号”。或
是一个控制流操作符,您需要| |
。这与OP检查的内容不同,并且不会打印日志消息。谢谢-然后当我使用我实际调用它时-如果使用返回false是否有效,除非检查属性(顶部属性,有效负载)
完全合法。确定。还有一个问题,关键字return是否也会在迭代时停止,即为什么需要break?为了简化代码并使其更好地阅读,我会使用名为empty\u poreties?
和如果属性为空则返回false?(…)break
是不需要的,但强烈建议使用,因为Ruby有许多不同的实现,而且return
基本上是对堆栈进行脏处理,而break
则不需要。后者可能有,也可能没有任何含义,但是break
更安全,更容易让GC知道发生了什么,更快地完成工作。
def foo
check_properties(top_properties, payload)
# do something with top_properties / payload
end
begin
foo
rescue PropertyError
log_err 'Something went wrong'
end