Since you know the positions of the characters to be removed, just remove 'em. The following method does that in four steps:
- Convert negative indices of characters to be deleted to non-negative indices.
- Sort the indices.
- Use Array#reverse_each to process the indices in reverse order.
- Remove the character at each index.
def remove_chars(str, *indices)
sz = str.size
indices.map { |i| i >= 0 ? i : sz + i }.sort.reverse_each { |i| str[i] = '' }
str
end
puts remove_chars('Set{[5, 6, 9]}', 4, -2 )
Set{5, 6, 9}
puts remove_chars('Set{[8, 4, "a", "[", 1]}', 4, -2 )
Set{8, 4, "a", "[", 1}
puts remove_chars('Set{[4, 8, "]", "%"]}', 4, -2 )
Set{4, 8, "]", "%"}
puts remove_chars('Set{[8, 4, "a", "[", 1]}', 23, 4, -2 )
Set{8, 4, "a", "[", 1
In the last example the string size is 24.
This method mutates the string on which it operates. If the string is not to be altered, execute
remove_chars(str.dup, 4, -2 )
or add a first line to the method str_cpy = str.dup and operate on str_cpy`.