我有一个动态字符串(在Ruby程序中),如果它超过91个字符,我需要拆分它。我需要将它分成关闭逗号','char。
的部分字符串示例:
"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41"
谢谢!
答案 0 :(得分:6)
这就是你需要的:
string.split(',').in_groups_of(90, false)
结果:
> str.split(',').in_groups_of(10, false)
=> [["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
["11", "12", "13", "14", "15", "16", "17", "18", "19", "20"],
["21", "22", "23", "24", "25", "26", "27", "28", "29", "30"],
["31", "32", "33", "34", "35", "36", "37", "38", "39", "40"],
["41"]]
或具有连接值的数组:
str.split(',').in_groups_of(10, false).map {|s| s.join(',')}
结果:
> str.split(',').in_groups_of(10, false).map {|s| s.join(',')}
=> ["1,2,3,4,5,6,7,8,9,10",
"11,12,13,14,15,16,17,18,19,20",
"21,22,23,24,25,26,27,28,29,30",
"31,32,33,34,35,36,37,38,39,40",
"41"]
<强>更新强>
使用纯Ruby(不是Rails):
str.split(',').each_slice(10).to_a
或加入:
str.split(',').each_slice(10).map {|s| s.join(',')}
答案 1 :(得分:1)
试试这个
str.split(',') if str.length>91
答案 2 :(得分:0)
我假设你需要一些带String的东西并返回一个Array,其中Array的每个元素都是一个长度为91或更短的字符串。但是,在分割分隔符之前,您希望生成的字符串尽可能长。
a = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41"
def my_split(str, delimiter, max_length)
return [str] if str.length <= max_length
i = str.rindex(delimiter, max_length)
the_rest = my_split(str[i+1..-1], delimiter, max_length)
return [str[0..i-1]] + the_rest
end
for r in my_split(a, ',', 90)
puts "#{r}:Length: #{r.length.to_s}"
end
结果:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33:Length: 89
34,35,36,37,38,39,40,41:Length: 23