Last Updated: February 06, 2018
·
809
· rafaelcgo

Ruby Simple Transformation String Method

def transform_string(string)
  transformed_string = string.dup
  char_positions = []

  ('A'..'Z').each do |char|
    break if char_positions.size >=2

    position = string.index(char)
    next if position.nil?

    char_positions << {char: char, position: position}
  end

  transformed_string[char_positions.first[:position]] = char_positions.last[:char]
  transformed_string[char_positions.last[:position]]  = char_positions.first[:char]

  transformed_string
end