我试图将除法运算符/
添加到String
中,这需要一个整数。
运算符应该生成一个字符串数组。数组的大小是给定的整数,其元素是原始字符串的子字符串,因此当按顺序连接时,产生原始字符串。
如果字符串长度不能被整数整除,则某些子字符串应该比其他字符长(一个字符)。两个字符串的长度不应超过一个,任何较长的字符串都应出现在较短的字符串之前。
如下所示:
"This is a relatively long string" / 7
# => ["This ", "is a ", "relat", "ively", " lon", "g st", "ring"]
我怎么开始?
发布于 2016-03-02 08:10:03
你可以使用递归。
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]
发布于 2016-03-02 06:29:26
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"]
发布于 2016-03-02 08:47:46
这样做是可行的:
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
是将数组分成n组的Rails方法。
https://stackoverflow.com/questions/35737748
复制相似问题