How to remove characters from String at specific index in Ruby

I have several lines:

  • 'Set{[5, 6, 9]}'

  • 'Set{[8, 4, "a", "[", 1]}'

  • 'Set{[4, 8, "]", "%"]}'

I want to remove square brackets from indices 4 and -2 from these lines so that I have:

  • 'Set{5, 6, 9}'

  • 'Set{8, 4, "a", "[", 1}'

  • 'Set{4, 8, "]", "%"}'

How can i do this?

+3


source to share


2 answers


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 pattern '{[' or ']} in the middle of the line and want to store it there, and if you are sure of the position relative to the start and end of the line each time, you can 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}"

      

+4


source


Since you know the positions of the characters to be removed, just remove them. The following method does this in four steps:

  • Convert negative indices of characters to be removed to non-negative indices.
  • Sorting indexes.
  • Use Array # reverse_each to reverse the indexes.
  • Remove 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 row size is 24.

This method mutates the string it is running on. If the line shouldn't be changed, do

remove_chars(str.dup, 4, -2 )

      

or add the first line to the method str_cpy = str.dup

and act on str_cpy`.

+1


source







All Articles