John John - 2 months ago 7
Ruby Question

how to expand a string in ruby based on some condition?

i have a string

a5bc2cdf3
. i want to expand this string to
aaaaabcbccdfcdfcdf
. in the string after
a
there is a number
5
. so here in the resultant string should contain
5
consecutive "a" s. and after "bc" again there is a number
2
, so in the resultant string
bc
should appear
2
times consecutively. similarly
cdf
should repeat
3
times consecutively in the resultant string.

input =>
a5bc2cdf3
, output =>
aaaaabcbccdfcdfcdf
how can i do this in a ruby method?

def get_character("compressed_string",index)
expanded_string = calculate_expanded_string(compressed_string)
required_char = expanded_string(char_at, index_number(for eg 3))
end

def calculate_expanded_string(compressed_string)
return expanded
end

Answer

You may use a regex like

.gsub(/([a-zA-Z]+)(\d+)/){$1*$2.to_i}

See the Ruby online demo

The /([a-zA-Z]+)(\d+)/ will match stubstrings with 1+ letters (([a-zA-Z]+)) and 1+ digits ((\d+)) and will capture them into 2 groups that are later used inside a block to return the string you need.

Note that instead of [a-zA-Z] you might consider using \p{L} that can match any letters.

EDIT:

You want to break out of gsub once the specified index is reached in the original "compressed" string. It is still possible, see this Ruby demo:

s = 'a5bc2cdf3'                # input string
index = 5                      # break index
result = ""                    # expanded string
s.gsub!(/([a-zA-Z]+)(\d+)/){   # regex replacement
    result << $1*$2.to_i       # add to the resulting string
    break if Regexp.last_match.end(0) >= index  # Break if the current match end index is bigger or equal to index
}
puts result[index]            # Show the result
# => b

For brevity, you may replace Regexp.last_match with $~.