我开始学习Ruby,需要一些帮助吗?方法.
以下代码工作得很好:
x = 'ab.c'
if x.include? "."
puts 'hello'
else
puts 'no'
end
Run Code Online (Sandbox Code Playgroud)
但是当我以这种方式编码时:
x = 'ab.c'
y = 'xyz'
if x.include? "." || y.include? "."
puts 'hello'
else
puts 'no'
end
Run Code Online (Sandbox Code Playgroud)
如果我运行时给我错误:
test.rb:3: syntax error, unexpected tSTRING_BEG, expecting keyword_then or ';' o
r '\n'
if x.include? "." || y.include? "."
^
test.rb:5: syntax error, unexpected keyword_else, expecting end-of-input
Run Code Online (Sandbox Code Playgroud)
这是因为包括?方法不能有句柄逻辑运算符?
谢谢
Stu*_*t M 12
另一个答案和评论是正确的,你只需要在你的论证中加入括号,因为Ruby的语言解析规则,例如,
if x.include?(".") || y.include?(".")
Run Code Online (Sandbox Code Playgroud)
您也可以像这样构建条件,当您向搜索添加更多数组时,这将更容易扩展:
if [x, y].any? {|array| array.include? "." }
puts 'hello'
else
puts 'no'
end
Run Code Online (Sandbox Code Playgroud)
有关Enumerable#any?详细信息,请参阅
meg*_*gas 11
这是因为Ruby解析器,它无法识别传递参数和逻辑运算符之间的区别.
只需稍微修改一下代码,就可以区分Ruby解析器的参数和运算符.
if x.include?(".") || y.include?(".")
puts 'hello'
else
puts 'no'
end
Run Code Online (Sandbox Code Playgroud)