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'.
('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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With