Ruby字符串包括什么?两个或多个语句
我是编程初学者,从ruby开始。现在我试着搜索文档,看看是否包括患者。我通过以下代码实现了此任务:Ruby字符串包括什么?两个或多个语句,ruby,Ruby,我是编程初学者,从ruby开始。现在我试着搜索文档,看看是否包括患者。我通过以下代码实现了此任务: @patients.each do |patient| if document.include? patient.nachnahme || document.include? patient.vorname arr << a end end 那我做错了什么?我如何定义我的ruby代码只在以下情况下运行: document.include? patient.nachn
@patients.each do |patient|
if document.include? patient.nachnahme || document.include? patient.vorname
arr << a
end
end
那我做错了什么?我如何定义我的ruby代码只在以下情况下运行:
document.include? patient.nachnahme || document.include? patient.vorname
这两种说法都是正确的吗?把它写成
if document.include? patient.nachnahme or document.include? patient.vorname
试图在此处重现该问题:
"aaa".include? "a" or "bb".inlcude? "v"
# => true
"aaa".include? "a" || "bb".inlcude? "v"
# ~> -:2: syntax error, unexpected tSTRING_BEG, expecting ')'
# ~> ...include? "a" || "bb".inlcude? "v");$stderr.puts("!XMP1374693...
# ~> ...
注意
始终考虑使用<强>和< /强>和<强>或< /强>运算符进行控制流操作。
您需要做的是将
()
放在包含?
调用周围
document.include?(patient.nachnahme) || document.include?(patient.vorname)
当您执行双条件时,Ruby往往会有点困惑,因为从技术上讲,您可以调用:
# Not what you are intending
document.include?(patient.nachnahme || document.include? patient.vorname)
可能是优先权问题。试试:
if(document.include?patient.nachnahme)|(document.include?patient.vorname)
。效果很好!当document.include?(patient.nachnahme)| | document.include?(patient.vorname)这两个语句都错误时会发生什么?那么if
表达式将为false,并且在结束结束之前的if
后面的语句将不会被执行!当document.include?(patient.nachnahme)| | document.include?(patient.vorname)这两个语句都错误时会发生什么?您也可以使用非常弱的绑定或。它与混淆无关,而与;-)欢迎你不同意。我是基于很多经验,加上上面说:和或关键字被禁止。这不值得。请始终使用&&和| |。
同时在所有其他方法调用的参数周围使用括号。
我支持@Priti。在表达式或参数中使用强绑定运算符(如|
),在控制流中使用松散绑定运算符(如或
)。有上百种风格指南,有些禁止使用,有些则需要。每个人都有自己的。
# Not what you are intending
document.include?(patient.nachnahme || document.include? patient.vorname)