Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - unless multiple conditions

I'm trying to substitute an expression unless the expression is one of two values.

def substitute_string (string)
  string.gsub('abc', 'xyz') unless string == ('dabc' || 'eabc')
end

substitute_string('jjjjjabc')
=> 'jjjjjxyz'

substitute_string('dabc')
=> 'dabc'

substitute_string('eabc')
=> 'exyz'

I expected substitute_string('eabc') to return ('eabc') since I stated that in the unless block, which I passed two values.

I don't understand why this doesn't work, and what I can do to make 'eabc' return 'eabc'.

like image 669
Darkmouse Avatar asked Sep 30 '22 04:09

Darkmouse


1 Answers

('dabc' || 'eabc') is a boolean expression that evaluates to true and returns 'dabc'.

Use two or's:

unless string == 'dabc' || string == 'eabc'

Or use =~ (regex pattern match)

unless string =~ /(dabc|eabc)/

Since you indicated you're using Rails, you can also use in? like this:

unless string.in? ['dabc', 'eabc']

like image 135
Logan Serman Avatar answered Oct 03 '22 09:10

Logan Serman