Origin
Origin

Reputation: 27

OR condition in `if` statement

Why is

if name.eql? 'Name1' || name.eql? 'Name2'
  # doSomething
end

not allowed in Ruby? What is the good practice to do this in Ruby?

Upvotes: 1

Views: 81

Answers (3)

Sagar Pandya
Sagar Pandya

Reputation: 9497

You can use a case-expression:

case name
when 'Name1', 'Name2'
  # do something
when 'Name3'
  # do something else
else
  # if all else fails
end

Upvotes: 2

PhilVarg
PhilVarg

Reputation: 4820

ruby gives us the option to omit parenthesis and delegate the responsibility to the interpreter. what you've done is confuse the ruby interpreter because your lack of parentheses is ambiguous. Ie, ruby can't figure out what you're trying to do

this can be viewed a number of ways if we specify each parens

if(name.eql?('Name1') || name.eql?('Name2'))

if(name.eql?('Name1' || name.eql?('Name2'))

if(name.eql?('Name1')) || name.eql?('Name2')

a good practice is to specify parens when it starts to become ambiguous. Here that would mean putting them on the method arguements

if name.eql?('Name1') || name.eql?('Name2')

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230461

What is the good practice to do this in ruby?

Parenthesizing method calls to avoid silly ambiguities.

if name.eql?('Name1') || name.eql?('Name2')

Upvotes: 6

Related Questions