Ruby 1.8.7 で文字列をマージしたいのですが、助けてください。
s1 = "abc(1,,,,)"
s2 = "abc(,,3,,)"
s3 = "abc(,2,,,)"
s4 = "abc(,,,,5)"
出力は次のようになります。
s = "abc(1,2,3,,5)"
これを実現するためにRuby 1.8.7で利用できる組み込み関数はありますか?
もしかしてこういうこと?おそらく十分に一般的ではありません...
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)"