Методы Ruby для замены определенных символов в строке

Чтобы заменить определенные символы в строке Ruby, вы можете использовать различные методы. Вот несколько примеров:

  1. Использование метода gsub:

    string = "Hello, World!"
    new_string = string.gsub("o", "e") # Replaces all occurrences of "o" with "e"
    puts new_string # Output: Helle, Werld!
  2. Использование метода tr:

    string = "Hello, World!"
    new_string = string.tr("o", "e") # Replaces all occurrences of "o" with "e"
    puts new_string # Output: Helle, Werld!
  3. Использование регулярных выражений с методом gsub:

    string = "Hello, World!"
    new_string = string.gsub(/o/, "e") # Replaces all occurrences of "o" with "e"
    puts new_string # Output: Helle, Werld!
  4. Использование метода subдля замены только первого вхождения:

    string = "Hello, World!"
    new_string = string.sub("o", "e") # Replaces the first occurrence of "o" with "e"
    puts new_string # Output: Helle, World!
  5. Использование метода tr_sдля замены последовательных вхождений:

    string = "Hello, World!"
    new_string = string.tr_s("o", "e") # Replaces consecutive occurrences of "o" with a single "e"
    puts new_string # Output: Helle, World!