【问题标题】:Ruby syntax "OR" operator [duplicate]Ruby语法“OR”运算符[重复]
【发布时间】:2015-10-22 13:40:57
【问题描述】:

我有一个 Rails 项目,我的一个课程有:

def include_stuff?(str)
  str.include? '.' || str.include? '-'
end

这只是给我:

syntax error, unexpected tSTRING_BEG, expecting keyword_end (SyntaxError)
cpf.include? '.' || cpf.include? '-'
                                  ^

我把代码改成:

def include_stuff?(str)
  str.include? '.' or str.include? '-'
end

并且没有抛出任何错误。

我也试过了,成功了:

def include_stuff?(str)
  str.include?('.') || str.include?('-')
end

为什么 Ruby 不能理解带有双管道的语句,但可以理解带有 or 运算符的语句。

我正在使用 Ruby 2.2.2

【问题讨论】:

  • 优先规则,朋友。优先规则。

标签: ruby-on-rails ruby syntax-error


【解决方案1】:

||or 在 Ruby 中并不相同(请参阅 Difference between "or" and || in Ruby?),因为优先级不同。

所以你的陈述:

str.include? '.' or str.include? '-'

实际上等价于:

str.include?('.' || str.include?('-'))

【讨论】:

  • 继续逻辑。最后一条语句将变为 'str.include?('.')' 对吗?感谢您的快速回答,作为 SO 的新手,这里的速度非常棒。
  • @VictorSilvadosSantos 是的,没错。与大多数语言一样,如果逻辑析取的第一个参数(||or)为真,则甚至不计算第二个参数。
【解决方案2】:

这与运算符优先级有关。 or 远低于 ||

它试图将 cpf.include? '.' || cpf.include? '-' 解析为 cpf.include?('.' || cpf.include? '-' ) 并因为第二个 include? 没有括号而感到困惑。

http://www.techotopia.com/index.php/Ruby_Operator_Precedence

注意or|| 不是同一个东西。

http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/

结论

andor 尽管与 &&|| 有明显的相似之处,但它们的作用却截然不同。 and and or 是控制流修饰符,如ifunless。当以这种身份使用时,它们的低优先级是一种美德,而不是一种烦恼。

【讨论】:

  • 作为(无效)cpf.include?(('.' || cpf.include?) '-') 那么呢?
猜你喜欢
  • 2017-03-20
  • 2019-12-31
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
相关资源
最近更新 更多