我有以下情况:
type = "stringX"
someArray = ["stringX", "string1", "string2"]
case type
when "stringA"
puts "a"
when "stringB"
puts "b"
when someArray.any? { |x| x.include?(type) }
puts "x"
when "stringC"
puts "c"
end
我期望发生的是它会通过 case
并且一旦它评估 .any?
方法为真(因为它本身确实评估为true),它会put
"x"。然而,这不是这里发生的事情,它只是经历了 case
的其余部分,并在其下方的某处到达了 raise
。
我想知道这里发生了什么?
最佳答案
使用*
运算符
value = "stringX"
some_array = ["stringX", "string1", "string2"]
case type
when "stringA"
puts "a"
when "stringB"
puts "b"
when *some_array # notice the * before the variable name!
puts "x"
when "stringC"
puts "c"
end
这是如何工作的?
当 *some_array
检查 value
是否是 some_array
中的元素时
关于ruby - 。任何?在 case block 内未按预期进行评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41341510/