Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I logically OR two include? conditions in Ruby?

Tags:

ruby

I am starting learn Ruby, need some help with the include? method.

The below code works just fine:

x = 'ab.c'
if x.include? "." 
    puts 'hello'
else
    puts 'no'
end

But when I code it this way:

x = 'ab.c'
y = 'xyz'
if x.include? "." || y.include? "."
    puts 'hello'
else
    puts 'no'
end

If gives me error when I run it:

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

Is this because the include? method cannot have handle logic operator?

Thanks

like image 811
Andrew Avatar asked Apr 21 '13 00:04

Andrew


2 Answers

The other answer and comment are correct, you just need to include parenthesis around your argument due to Ruby's language parsing rules, e.g.,

if x.include?(".") || y.include?(".")

You could also just structure your conditional like this, which would scale more easily as you add more arrays to search:

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

See Enumerable#any? for more details.

like image 188
Stuart M Avatar answered Oct 18 '22 20:10

Stuart M


It's because of Ruby parser, it can't recognize the difference between the passing an arguments and logical operators.

Just modify your code a little bit to distinguish the arguments and operator for Ruby parser.

if x.include?(".") || y.include?(".")
    puts 'hello'
else
    puts 'no'
end
like image 11
megas Avatar answered Oct 18 '22 19:10

megas