加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何逻辑或两个包括? Ruby中的条件?

发布时间:2020-12-16 21:44:07 所属栏目:百科 来源:网络整理
导读:我开始学习 Ruby,需要一些帮助包括?方法. 以下代码工作正常: 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 当我运行它时
我开始学习 Ruby,需要一些帮助包括?方法.

以下代码工作正常:

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

这是因为包括吗?方法不能有句柄逻辑运算符?

谢谢

解决方法

另一个答案和评论是正确的,因为Ruby的语言解析规则,你只需要在你的参数周围加括号,
if x.include?(".") || y.include?(".")

您也可以像这样构建您的条件,当您添加更多的数组进行搜索时,它将更容易扩展:

if [x,y].any? {|array| array.include? "." }
  puts 'hello'
else
  puts 'no'
end

详见Enumerable#any?.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读