在 Ruby 中比较序列
假设我必须(中小型)数组:
tokens = ["aaa", "ccc", "xxx", "bbb", "ccc", "yyy", "zzz"]
template = ["aaa", "bbb", "ccc"]
如何确定 tokens
是否包含 template
的所有条目(按相同的顺序)?
(请注意,在上面的示例中,应忽略第一个“ccc”,从而导致由于最后一个“ccc”而导致匹配。)
Assuming I have to (small-to-medium) arrays:
tokens = ["aaa", "ccc", "xxx", "bbb", "ccc", "yyy", "zzz"]
template = ["aaa", "bbb", "ccc"]
How can I determine whether tokens
contains all entries of template
, in that same order?
(Note that in the example above, the first "ccc" should be ignored, resulting in a match due to the last "ccc".)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是一个单行条件:
示例:
This is a one-liner condition:
Example:
这是另一个想法,如果阵列是中小型的,它可能会工作得很好。
它只是将标记转换为正则表达式,并尝试将模板与其进行匹配。
(这也会将空模板视为与令牌匹配,因此如果您不希望这样做,只需显式处理这个极端情况)
Here's another idea, if the arrays are small-to medium, it might work fine.
It just converts the tokens into a regexp and tries to match the template against it.
(This will also treat empty template as if it matches tokens, so if you don't want that, just handle this corner case explicitly)
如果结果为空,只需从第二个数组中减去第一个数组
即可在此处阅读有关数组的更多信息 http://www.ruby-doc.org/core/classes/Array.html#M000273
如果顺序很重要,则使用 <=>上面的链接中再次描述了运算符
Just subtract the first array from the second array if the result is empty you have your match
Read more about arrays here http://www.ruby-doc.org/core/classes/Array.html#M000273
If order is important then use <=> operator again described in the link above
这适用于您的示例数据。
This works for your sample data.
我认为通过递归来做到这一点是最干净的:
所以:
Cleanest, I think, to do this via recursion:
so:
manatwork 提供的解决方案很好,但对我来说,这是一个更红宝石风格的解决方案:
Solution provided by manatwork is good, but here is one that seems more ruby-ish to me: