1

How do you do the reverse of

asd = 'qwe'

asd.match('qwe') do
  p 'it matches'
else
  p 'it doesnt match'
end

By reverse, I mean

asd.does_not_match('qwe') do
  p 'it doesnt match'
else
 p 'it matches'
end

What is the syntax for 'doesn't match'?

5
  • 2
    why not just flip the contents of the blocks? Commented Jan 21, 2014 at 23:23
  • putting a negation bang !asd.match('qwe') Commented Jan 21, 2014 at 23:24
  • 1
    Have you seen this? Commented Jan 21, 2014 at 23:24
  • 3
    Does that even work? How are you doing an else without an if? Commented Jan 21, 2014 at 23:24
  • You definitely need to use an if statement to make this work properly in the first place --> add if before asd.match('qwe') and then remove do. Commented Jan 22, 2014 at 0:33

4 Answers 4

7

To get the opposite effect of if you could use unless like this:

unless asd.match('qwe')
  puts 'it doesnt match'
else
  puts 'it matches'
end

or you could use if but with a "bang" (exclamation mark) at the beginning of the expression you wish to 'reverse' the boolean value of that expression.

if !asd.match('qwe')
  puts 'it doesnt match'
else
  puts 'it matches'
end

Have a read up on conditional statements in ruby to find out more.

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

1 Comment

Thanks, just what I needed! I understand about the conditional statement, just not sure how to implement that with match method. :D
4
result = asd.match('qwe') ? "it matches" :  "it doesn't match"

puts result

it matches

result = !asd.match('qwe') ? "it matches" :  "it doesn't match"

puts result

it doesn't match

Ternary operator will make your code simple, try it too...

2 Comments

oh, does ternary operator support multiple line commands in ruby? I came from C/C++, and ternary basically only does 1 line command.
Functionality of ternary operator does not change, it is same as C/C++.
1

Use the operator '!' to invert the logic of a statement. Just change the first line to

!(asd.does_not_match('qwe')) do

*I like to include parentheses around the whole statement just because it's cleaner to see what you're negating

Comments

0

you could also do

unless asd.match('qwe') do
  puts "It matches."
else
  puts "It doesn't match."
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.