Ruby String Match

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'?

Answers


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.


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...


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


Need Your Help

How to create a .BAT file to download file from HTTP\ftp server?

windows ftp batch-file

How to create a .BAT file to download file or folder from FTP server? (and replace with it existing file) (we have links like ftp://me:mypass@example.com/file.file (or http://example.com/file.file)...

Add new rows to key from a range

sql sql-server key sql-server-2012 range

Hi I have a question how to expand my key coloumn with data between two coloumns