这个 Ruby 案例控制代码有什么问题?

What is wrong with this Ruby case control code?

def identify_class(obj)

result = case obj
when obj.kind_of? Hacker  then "It's a Hacker!"
when obj.kind_of? Submission then "It's a Submission!"
when obj.kind_of? TestCase then "It's a TestCase!"
when obj.kind_of? Contest then "It's a Contest!"
    end

puts result   

end

syntax error, unexpected tCONSTANT, expecting keyword_then or ',' or';' or '\n'

在 result = case obj 语句和一堆

syntax error, unexpected keyword_when, expecting keyword_end

在每个 when 语句之后,最后输入错误结束。

如果我删除除一个之外的所有 when 语句,即使第二个错误消失了,也无法正常工作。

我试过使用 if else 梯形图,但这也行不通

如果 obj.kind_of 可以用一首单曲吗?黑客放 "It's a ...."

在Ruby中有两种case表达式,你好像混淆了它们。第一个与 if...elsif...end 表达式基本相同,如下所示:

case
when boolean_expression
  # code executed if boolean_expression is truthy
when other_expression
  # code executed if other_expression is truthy
# other whens ...
end

请注意第一个 when 之前的 case 之后没有任何内容。在这种类型的 case 语句中,与第一个计算结果为真的表达式关联的代码将被执行,其余的都不会。

另一种 case 语句接受一个参数并将该参数与每个 when 子句进行比较:

case obj
when type1
  # some code if type1 === obj
when other_type
  # some code if other_type === obj
# other whens ...
end

这里有一个 case 的参数(本例中为 obj)。这将依次使用 === 与每个 when 子句的参数进行比较,并且关联代码是 运行 对于第一个比较为真的子句。

注意这种case可以像第一种那样写:

case
when type1 === obj
# etc...

在您的例子中,您从 case obj 开始,这表示第二种类型。然后,您可以在每个 when 子句中使用 obj,就像在第一种子句中一样。

(你得到的实际错误实际上只是一个语法错误,由 Ruby 语法中的一点歧义引起,但即使你修复了你的代码也不会像你想的那样工作期待。)

模块 overrides === to check if the arg is an instance,所以为了您的使用,您可以这样做:

result = case obj
when Hacker  then "It's a Hacker!"
when Submission then "It's a Submission!"
when TestCase then "It's a TestCase!"
when Contest then "It's a Contest!"
end