【问题标题】:Case expression with no target object: should it be used?没有目标对象的案例表达式:应该使用它吗?
【发布时间】:2014-09-09 02:30:33
【问题描述】:

我知道你可以在没有目标对象的情况下使用 case 语句,如下所示:

case 
when condition1
  do_something1
when condition2
  do_something2
else
  do_something_else
end

这相当于:

if condition1
  do_something1
elsif condition2
  do_something2
else
  do_something_else
end

是否有任何理由允许在没有目标对象的情况下使用 case 表达式?在任何情况下都希望以这种方式使用 case 表达式?

【问题讨论】:

  • 不确定我是否理解这个问题,没有 no value 表达式,这是默认情况(就像您在类 C 语言中看到的那样)。

标签: ruby syntax


【解决方案1】:

它可以用来检查多个表达式。考虑这个例子:

print "Enter first string: "
some_string = gets.chomp
print "Enter second string: "
some_string1 = gets.chomp
puts case
when some_string.match(/\d/)
  'String has numbers'
when some_string1.match(/[a-zA-Z]/)
  'String has letters'
else
  'String has no numbers or letters'
end

在这里,您必须检查两个不同的变量。或许专家们有不同的看法。

【讨论】:

    【解决方案2】:

    实际上没有区别,空的case 语句不会调用===,因为没有什么可调用的。示例:

    class CaseExample
    
      def ===(other)
        puts "received #{other}"
        super(other)
      end
    
    end
    

    当这样调用时:

    case
      when CaseExample.new()
        puts "got here"
    end
    

    将打印:

    "got here"
    

    同时:

    case "me"
      when CaseExample.new()
        puts "got here"
    end
    

    它将打印:

    "received me"
    

    如果没有案例对象,我宁愿选择if/elsif,因为意图会更清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 2012-02-21
      • 2020-05-29
      • 2013-11-26
      • 1970-01-01
      相关资源
      最近更新 更多