我想在Ruby 1.8.7中合并Strings,请帮忙。
s1 = "abc(1,,,,)"
s2 = "abc(,,3,,)"
s3 = "abc(,2,,,)"
s4 = "abc(,,,,5)"
,输出应为:
s = "abc(1,2,3,,5)"
Ruby 1.8.7中是否有可用于实现此功能的内置函数?
答案 0 :(得分:1)
也许这样的事情?可能不够通用......
def merge *strings
result_array = strings.inject([]) do |merged_array,string|
string_content = string[/\((.+?)\)/, 1].split(',', -1)
string_content.each_with_index do |elem,idx|
if !merged_array[idx] || merged_array[idx].empty?
merged_array[idx] = elem
end
end
merged_array
end
$` + '(' + result_array.join(',') + ')' + $'
end
p merge(s1, s2, s3, s4) #=> "abc(1,2,3,,5)"