在Ruby中序列比较 [英] comparing sequences in Ruby

查看:103
本文介绍了在Ruby中序列比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有(小到中等)阵列:

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?

(注意,在上面的例子中,第一个CCC应忽略,导致匹配由于最后的CCC。)

(Note that in the example above, the first "ccc" should be ignored, resulting in a match due to the last "ccc".)

推荐答案

清洁,我认为,通过递归来做到这一点:

Cleanest, I think, to do this via recursion:

class Array
  def align(other)
    if pos = index(other.first)
      other.size == 1 || slice(pos..-1).align(other.drop(1))
    end
  end
end

这样:

[1,2,3,4,3,2,1].align([1,2,3])
=> true
[1,2,3,4,3,2,1].align([1,4,1])
=> true
[1,2,3,4,3,2,1].align([1,4,2,3])
=> nil

这篇关于在Ruby中序列比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆