0

I have a Rails project and one of my classes has:

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

Which just give me:

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

I changed the code to:

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

And no error was thrown.

I tried this too, with success:

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

Why can't Ruby understand the statement with double pipe, but can understand the statement with the or operator.

I'm using Ruby 2.2.2

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Victor Santos
  • 61
  • 1
  • 7

2 Answers2

3

|| and or are not the same in Ruby (see Difference between "or" and || in Ruby?) because of precedence.

So your statement:

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

is actually equivalent to:

str.include?('.' || str.include?('-'))
Community
  • 1
  • 1
eirikir
  • 3,802
  • 3
  • 21
  • 39
  • Just continuing the logic. The last statement will become ' str.include?('.') ' right? And thanks for the fast answer, as a newbie in SO, the velocity here are awesome. – Victor Santos Jul 31 '15 at 01:44
  • @VictorSilvadosSantos Yes, that's correct. As in most languages, if the first argument of a logical disjunction (whether `||` or `or`) is truthy, the second argument isn't even evaluated. – eirikir Jul 31 '15 at 02:04
2

It's to do with operator precedence. or is much lower than ||.

It's trying to parse cpf.include? '.' || cpf.include? '-' as cpf.include?('.' || cpf.include? '-' ) and gets confused as the second include? doesn't have brackets.

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

Note or and || are not the same thing.

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

Conclusion

and and or, despite an apparent similarity to && and ||, have very different roles. and and or are control-flow modifiers like if and unless. When used in this capacity their low precedence is a virtue rather than an annoyance.

Community
  • 1
  • 1
Nigel Thorne
  • 21,158
  • 3
  • 35
  • 51