Huy Tran Huy Tran - 6 months ago 31
Ruby Question

How to remove characters from String at specific index in Ruby

I have some strings in Ruby that look like this

'Set{[5, 6, 9]}'
,
'Set{[8, 4, "a", "[", 1]}'
,
'Set{[4, 8, "]", "%"]}'
. I want to remove the square brackets at index 4 and -2 from these strings so that I have
'Set{5, 6, 9}'
,
'Set{8, 4, "a", "[", 1}'
,
'Set{4, 8, "]", "%"}'
. How can I do that?

Answer Source

I think you want this:

>> string = 'Set{[8, 4, "a", 6, 1]}'
=> "Set{[8, 4, \"a\", 6, 1]}"
>> string.gsub('{[', '{').gsub(']}', '}')
=> "Set{8, 4, \"a\", 6, 1}"

If there is any danger that you might see the '{[' or ']}' pattern in the middle of the string and want to preserve it there, and if you are sure of the position relative to the start and end of the string each time, you could do this:

>> string = 'Set{[8, 4, "a", 6, 1]}'
>> chars = string.chars
>> chars.delete_at(4)
>> chars.delete_at(-2)
>> chars.join
=> "Set{8, 4, \"a\", 6, 1}"