ruby - 我如何在逻辑上或两个包括? ruby 的条件?

标签 ruby

我刚开始学习 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/

相关文章:

mysql - Ruby on Rails,保存!返回 true 但数据库行未更改(仅在生产中;在开发中工作正常)

javascript - rails : Anchor Tag to jump to location on same page without sending a new request and having to re-render the page

mysql - Ruby Array - 计算重叠的快速方法

ruby-on-rails - 从 rails 3.2.12 更改为 3.2.13 时,是什么导致极度缓慢

ruby-on-rails - 在 rails 上使用选择和数字 ruby 形成

ruby - 无法使用 implode 命令卸载 rvm

ruby-on-rails - 如何将时间字段解析为小时、分钟和秒?

ruby-on-rails - bundle 更新卡住

ruby - 安装iruby时出现rbczmq错误

Ruby Net::HTTP 超时