0

I have this very simple test code:

s="helloCustomer"

is_contain_customer = s=='helloCustomer' || s.include? 'Customer' ? 'YES' : 'NO'

I got error message Unexpected tSTRING_BEG for the 2nd line in the code.

Why?

3 Answers 3

5

In addition to the syntax error (you need parentheses around method args if the syntax is ambiguous), your code is not as clear as it could be.

You're using the higher precedence of || vs ? : to cause the expression to ultimately return 'YES' or 'NO'

For the sake of readability and maintainability, I suggest that you add parentheses to make the intent clear:

is_contain_customer = 
     (s=='helloCustomer' || s.include?('Customer')) ? 'YES' : 'NO'

Also, if you're using Rails or another MVC system, it'd be better to use your View layer to convert the data (the boolean value) to a string.

Sign up to request clarification or add additional context in comments.

2 Comments

Agreed, it is better to be explicit in this case.
Without parens, it is just plain confusing.
3

Wrap your s.include? in parentheses:

s.include?('Customer')

Comments

1

As Larry K said above, parenthesis both fixes the error and makes it more readable; However in this case I think I would make it a touch more verbose for readability:

if (s=='helloCustomer' || s.include?('Customer'))
  is_contain_customer = 'YES'
else
  is_contain_customer = 'NO'
end

Also as Larry K said, if this is in a controller or model, I'd use true or false, and then let the view decide what text to display. If this is used for logic later on it saves you from having to do something silly like if is_contain_customer=='YES' when it could simply be if is_contain_customer

If you need to do this more than once, I'd go one step further and make a function out of it.

def is_customer?(s)
  s=='helloCustomer' || s.include?('Customer')
end

This makes it easy to use in logic or in view helpers (depending on where you define it)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.