拆分字符串以获取 Ruby 的所有子字符串的最佳方法是什么? [英] What is the best way to split a string to get all the substrings by Ruby?

查看:26
本文介绍了拆分字符串以获取 Ruby 的所有子字符串的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,单词stack",我想得到一个像这样的数组:

For example, the words "stack", I want to get an array like:

['s', 'st', 'sta', ... 'stack', 't', 'ta', ... , 'c', 'ck', 'k']

我是用这样的代码做到的:

I did this by such code:

def split_word(str)
  result = []
  chas = str.split("")
  len = chas.size
  (0..len-1).each do |i|
    (i..len-1).each do |j|
      result.push(chas[i..j].join)
    end
  end
  result.uniq
end

有没有更好更干净的方法来做到这一点?谢谢.

Is there better and clean way to do that? Thanks.

推荐答案

def split_word s
  (0..s.length).inject([]){|ai,i|
    (1..s.length - i).inject(ai){|aj,j|
      aj << s[i,j]
    }
  }.uniq
end

而且你也可以考虑使用Set 而不是 Array 作为结果.

And you can also consider using Set instead of Array for the result.

PS:这是另一个想法,基于阵列产品:

PS: Here's another idea, based on array product:

def split_word s
  indices = (0...s.length).to_a
  indices.product(indices).reject{|i,j| i > j}.map{|i,j| s[i..j]}.uniq
end

这篇关于拆分字符串以获取 Ruby 的所有子字符串的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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