Ruby Simple Transformation String Method

Posted on
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

Leave a Reply

Your email address will not be published.