具有多个变量的 Ruby case 语句
当您需要针对单个变量匹配条件时,Ruby 有一个相当强大的 case..when..else
构造。在不简单嵌套 case
语句的情况下将条件与多个变量进行匹配的“规范”方法是什么?
将多个变量包装在一个数组中(例如 [x, y]
)并对其进行匹配并不等效,因为 Ruby 不会应用神奇的 case ===
运算符到数组的元素;该运算符仅应用于数组本身。
我将继续用社区维基的答案来回应这个问题(失败的)。
Ruby has a fairly powerful case..when..else
construct for when you need to match criteria against a single variable. What is the "canonical" way to match criteria against multiple variables without simply nesting case
statements?
Wrapping multiple variables in an array (like [x, y]
) and matching against it isn't equivalent, because Ruby won't apply the magical case ===
operator to the elements of the array; the operator is only applied to the array itself.
I'm going to go ahead and respond with a community-wiki answer with a (defeated) stab at this question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要使用
if..elsif..else
,并确保要匹配的变量出现在===
运算符的右侧(这就是case
本质上所做的)。例如,如果您想根据某些条件匹配
x
和y
:You need to use an
if..elsif..else
, and ensure that the variables you want to match against appear on the right-hand side of the===
operator (which is whatcase
essentially does).For example, if you want to match
x
andy
against some criteria:这是添加
===
的简单方法:This is a simplistic way to add
===
:如果这种模式在您的代码中足够常见以保证经济的表达,您可以自己做:
If this pattern is common enough in your code to warrant economical expression, you can do it yourself:
由于 Ruby 的
when
关键字支持逗号分隔的值列表,因此您可以使用 splat*
运算符。当然,这是假设您引用的是数组中或可能成为数组的一组离散值。splat 运算符将参数列表转换为数组,正如在
不太为人所知的事实中经常看到的那样,它还执行逆操作 - 将数组转换为参数列表。
所以在这种情况下,你可以这样做
Since Ruby's
when
keyword supports a comma separated list of values, you could use the splat*
operator. This is, of course, assuming that you're referring to a set of discrete values that are in or could become an array.The splat operator converts a list of arguments into an array, as frequently seen in
Less well known is the fact that it also performs the inverse operation - turning an array into a list of arguments.
So in this case, you could do something like
我未经测试的解决方案是调用
.map(&:class)
,然后是when
语句中的数组My not battled tested solution is to call
.map(&:class)
and then is the array in thewhen
statements如果您正在使用字符串或可以轻松转换为字符串的内容,您可能会喜欢以下解决方案:
If you're working with strings, or something that converts to strings easily, you might like this solution: