【问题标题】:In Ruby, how do I break up a string given an array of indexes I want to break the string on?在 Ruby 中,如何在给定索引数组的情况下拆分字符串?
【发布时间】:2016-11-28 02:42:21
【问题描述】:

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

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

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

[3, 6, 10]

我有字符串

abcdefghijklmnopqrs

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

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

我该怎么做?

【问题讨论】:

  • 这是一个 ruby​​ 问题,而不是 rails 问题。

标签: arrays ruby string substring


【解决方案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

【讨论】:

    【解决方案2】:

    您可以使用 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"]
    

    【讨论】:

      【解决方案3】:
      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"] 
      

      【讨论】:

      • 直到Enumerable#each_cons。不错的答案;应该知道 Ruby 中会存在一个可以执行类似操作的方法。
      猜你喜欢
      • 2017-05-23
      • 2016-12-03
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 2018-01-03
      相关资源
      最近更新 更多