我有这个非常简单的测试代码:
s="helloCustomer"
is_contain_customer = s=='helloCustomer' || s.include? 'Customer' ? 'YES' : 'NO'
我在代码中的第二行收到错误消息意外的tSTRING_BEG 。
为什么?
答案 0 :(得分:5)
除了语法错误(如果语法不明确,你需要围绕方法args的括号),你的代码就不那么明确了。
你使用的是||的更高优先级vs? :使表达式最终返回“YES”或“NO”
为了便于阅读和维护,我建议你添加括号以明确意图:
is_contain_customer =
(s=='helloCustomer' || s.include?('Customer')) ? 'YES' : 'NO'
此外,如果您正在使用Rails或其他MVC系统,最好使用View层将数据(布尔值)转换为字符串。
答案 1 :(得分:3)
将s.include?
括在括号中:
s.include?('Customer')
答案 2 :(得分:1)
正如Larry K所说,括号既修正错误又使其更具可读性;但是在这种情况下,我想我会因为可读性而变得更加冗长:
if (s=='helloCustomer' || s.include?('Customer'))
is_contain_customer = 'YES'
else
is_contain_customer = 'NO'
end
同样,Larry K说,如果这是在控制器或模型中,我会使用true
或false
,然后让视图决定要显示的文本。如果稍后将其用于逻辑,则可以使您不必像if is_contain_customer=='YES'
那样做一些愚蠢的事情if is_contain_customer
如果您不止一次需要这样做,我会更进一步,从中做出一个功能。
def is_customer?(s)
s=='helloCustomer' || s.include?('Customer')
end
这使得在逻辑或视图助手中使用变得容易(取决于你定义它的位置)