【问题标题】:Ruby String Match红宝石字符串匹配
【发布时间】:2014-02-11 19:31:55
【问题描述】:

你怎么做的相反

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

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

【问题讨论】:

  • 为什么不直接翻转积木的内容呢?
  • 否定句!asd.match('qwe')
  • 你见过this吗?
  • 这行得通吗?没有 if 的 else 怎么办?
  • 您首先肯定需要使用if 语句才能使其正常工作 --> 在asd.match('qwe') 之前添加if,然后删除do

标签: ruby string match


【解决方案1】:

你也可以

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

【讨论】:

    【解决方案2】:
    result = asd.match('qwe') ? "it matches" :  "it doesn't match"
    
    puts result
    

    匹配

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

    不匹配

    三元运算符会让你的代码变得简单,也试试吧……

    【讨论】:

    • 哦,三元运算符是否支持ruby中的多行命令?我来自C/C++,三元基本上只做1行命令。
    • 三元运算符的功能不变,与C/C++相同。
    【解决方案3】:

    使用运算符“!”反转语句的逻辑。 只需将第一行更改为

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

    *我喜欢在整个语句周围加上括号,因为这样可以更清楚地看到你在否定什么

    【讨论】:

      【解决方案4】:

      要获得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​​ 中的 conditional statements 以了解更多信息。

      【讨论】:

      • 谢谢,正是我需要的!我了解条件语句,只是不确定如何使用 match 方法实现它。 :D
      猜你喜欢
      • 2019-10-23
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      相关资源
      最近更新 更多