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

查看:15
本文介绍了比较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?

(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

so:

[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天全站免登陆