如何对 Ruby 中的字符串应用除法运算符?

How do I apply a division operator on a string in Ruby?

我正在尝试将除法运算符 / 添加到 String,它需要一个整数。

运算符应生成一个字符串数组。数组的大小是给定的整数,它的元素是原始字符串的子字符串,这样当按顺序连接时,就会产生原始字符串。

如果字符串长度不能被整数整除,一些子串应该比其他的长(一个字符)。两个字符串的长度相差不得超过 1,并且较长的字符串应出现在较短的字符串之前。

像这样:

"This is a relatively long string" / 7
# => ["This ", "is a ", "relat", "ively", " lon", "g st", "ring"]

我该如何开始?

class String
  def /(num)
    partition_size = length / num
    if length % num == 0
      scan /.{#{partition_size}}/
    else
      scan /.{#{partition_size},#{partition_size + 1}}/
    end  
  end
end

这是我的解决方案,有点笨重但时间复杂度为 O(n)。

如果有任何边缘情况失败请告诉我:

class String
  def /(num)

    if num > self.length
      return [] # or whatever, since this is an edge case / can't be done
    end

    remainder = self.length % num
    result = []
    substr = ""

    i = 1
    while i <= self.length
      substr += self[i-1]

      if i % (self.length / num) == 0
        if remainder > 0
          substr += self[i]
          i += 1
          remainder -= 1
        end

        result << substr
        substr = ""
      end

      i += 1
    end

    result
  end
end

编辑: 重构 - 用子字符串替换子数组

class String
  def /(num)
      n, rem = self.size.divmod(num)
      p = 0
      res = []
      rem.times{res << self[p..p+n]; p+=n+1} 
      (num-rem).times{res << self[p...p+n]; p+=n}
      res
  end
end

p "This is a relatively long string" / 7

["This ", "is a ", "relat", "ively", " lon", "g st", "ring"]

你可以使用递归。

class String
  def /(n)
    return [self] if n==1
    m = (self.size.to_f/n).ceil
    [self[0...m]].concat(self[m..-1] / (n-1))
  end
end

str = "This would be a woefully short string had I not padded it out."

str / 7
  # => ["This woul", "d be a wo", "efully sh", "ort strin", "g had I n",
  #     "ot padded", " it out."] 


(str / 7).map(&:size)
  #=> [10, 10, 9, 9, 9, 9, 9]

这可行:

class String
  def /(n)
    chars.in_groups(n).map(&:join) 
  end
end

"This is a relatively long string" / 7
#=> ["This ", "is a ", "relat", "ively", " lon", "g st", "ring"]

in_groups 是一种 Rails 方法,它将数组拆分为 n 组。