【问题标题】:Using splat operator with when将 splat 运算符与 when 一起使用
【发布时间】:2017-11-17 14:56:22
【问题描述】:

案例陈述:

case x
when 1
  "one"
when 2
  "two"
when 3
  "three"
else
  "many"
end

使用 === 运算符进行评估。此运算符在when 表达式的值上调用,case 表达式的值作为参数。上面的case语句等价于:

if 1 === x
  "one"
elsif 2 === x
  "two"
elsif 3 === x
  "three"
else
  "many"
end

在这种情况下:

A = 1
B = [2, 3, 4]
case reason
when A
  puts "busy"
when *B
  puts "offline"
end

when *B 部分不能重写为*B === 2

这是关于 splat 运算符的吗? splat 运算符是关于赋值,而不是比较。 case语句如何处理when *B

【问题讨论】:

  • 第一个示例和第二个示例之间的细微差别:如果x 是一个方法,则它在第一个示例中只调用一次,但在第二个示例中最多调用三次。

标签: ruby splat


【解决方案1】:

但是 splat 运算符是关于赋值,而不是比较。

在这种情况下,* 转换为 array into an argument list

when *[2, 3, 4]

相当于:

when 2, 3, 4

就像在方法调用中一样:

foo(*[2, 3, 4])

相当于:

foo(2, 3, 4)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-22
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 2015-11-09
    • 2012-11-22
    相关资源
    最近更新 更多