0
我想在Ruby 1.8.7中合併字符串,請大家幫忙。Ruby String merge
s1 = "abc(1,,,,)"
s2 = "abc(,,3,,)"
s3 = "abc(,2,,,)"
s4 = "abc(,,,,5)"
和輸出應該是:
s = "abc(1,2,3,,5)"
是否有紅寶石1.8.7提供任何內置的功能來實現這一目標?
我想在Ruby 1.8.7中合併字符串,請大家幫忙。Ruby String merge
s1 = "abc(1,,,,)"
s2 = "abc(,,3,,)"
s3 = "abc(,2,,,)"
s4 = "abc(,,,,5)"
和輸出應該是:
s = "abc(1,2,3,,5)"
是否有紅寶石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)"