在Ruby中,如果给出一个我希望打破字符串的索引数组,如何分解字符串?

时间:2016-07-24 19:58:44

标签: arrays ruby string substring

我有这个表达式来获取给定字符串中的空格索引...

a = (0 ... cur_line.length).find_all { |i| cur_line[i,1] == ' ' }

我想要做的是获取上面表达式返回的索引,并使用它们来分解这些索引上的其他字符串。所以,例如,如果上面包含

[3,6,10]

我有字符串

abcdefghijklmnopqrs

然后我想要获取索引,使用它们来分解上面的字符串,并获得一个包含

的数组
[“abc”, “def”, “ghij”, “klmnopqrs”]

我该怎么做?

3 个答案:

答案 0 :(得分:1)

这应该是实现目标的最简单方法:

def split_by_indices(indices, string)
    result = []
    indices.unshift(0)
    indices.each_with_index do |val, index|
      result << string[val...(index == indices.length - 1 ? string.length : indices[index+1])]
    end
    result
end

答案 1 :(得分:1)

您可以使用Ruby的Enumerable#reduceString#slice方法,将哈希值作为初始值传递给reduce,以跟踪您所使用的新数组。重新创建,以及从字符串开始切片的指示。然后,每个索引将表示切片应该结束的位置,因此为了获得最终的字符串,我们将str.length添加为最终指标:

str = 'abcdefghijklmnopqrs'
indices = [3, 6, 10]

result = [*indices, str.length].reduce({ array: [], slice_from: 0 }) do |memo, index|
  memo[:array] << str.slice(memo[:slice_from]...index)
  memo[:slice_from] = index
  memo
end

p result[:array]
# => ["abc", "def", "ghij", "klmnopqrs"]

答案 2 :(得分:1)

a = [3, 6, 10]
s = 'abcdefghijklmnopqrs'
[0, *a, s.length].each_cons(2).map{|i,j| s[i...j]}
#=> ["abc", "def", "ghij", "klmnopqrs"]

显然,自2.3以来,Ruby也有Enumerable#chunk_while,但在这种情况下有点麻烦:

s.chars.each_with_index.chunk_while{|_,(_,i)| !a.member?(i)}.map{|n| n.map(&:first).join}
#=> ["abc", "def", "ghij", "klmnopqrs"]