簡體   English   中英

Ruby 字符串匹配

[英]Ruby String Match

你怎么做相反的

asd = 'qwe'

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

反過來,我的意思是

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

“不匹配”的語法是什么?

要得到相反的效果if你可以使用unless這樣的:

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

或者您可以使用if但希望在表達式的開頭加上“ bang”(感嘆號),以“反轉”該表達式的布爾值。

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

閱讀ruby中的條件語句以了解更多信息。

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

puts result

它匹配

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

puts result

不匹配

三元運算符將使您的代碼簡單,也可以嘗試...

使用運算符“!” 顛倒陳述的邏輯。 只需將第一行更改為

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

*我喜歡在整個語句中加上括號,因為這樣可以更清楚地看到您要否定的內容

你也可以這樣做

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM