我刚开始学习 Ruby,需要一些关于 include 的帮助吗?方法。
下面的代码工作得很好:
x = 'ab.c'
if x.include? "."
puts 'hello'
else
puts 'no'
end
但是当我这样编码时:
x = 'ab.c'
y = 'xyz'
if x.include? "." || y.include? "."
puts 'hello'
else
puts 'no'
end
如果在运行时出现错误:
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
是因为include吗?方法不能有句柄逻辑运算符?
谢谢
最佳答案
其他答案和评论是正确的,由于 Ruby 的语言解析规则,您只需要在论点周围加上括号,例如,
if x.include?(".") || y.include?(".")
您也可以像这样构建您的条件,当您添加更多数组进行搜索时,它会更容易扩展:
if [x, y].any? {|array| array.include? "." }
puts 'hello'
else
puts 'no'
end
参见 Enumerable#any?
了解更多详情。
关于ruby - 我如何在逻辑上或两个包括? ruby 的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16126863/