Чтобы заменить определенные символы в строке Ruby, вы можете использовать различные методы. Вот несколько примеров:
-
Использование метода
gsub:string = "Hello, World!" new_string = string.gsub("o", "e") # Replaces all occurrences of "o" with "e" puts new_string # Output: Helle, Werld! -
Использование метода
tr:string = "Hello, World!" new_string = string.tr("o", "e") # Replaces all occurrences of "o" with "e" puts new_string # Output: Helle, Werld! -
Использование регулярных выражений с методом
gsub:string = "Hello, World!" new_string = string.gsub(/o/, "e") # Replaces all occurrences of "o" with "e" puts new_string # Output: Helle, Werld! -
Использование метода
subдля замены только первого вхождения:string = "Hello, World!" new_string = string.sub("o", "e") # Replaces the first occurrence of "o" with "e" puts new_string # Output: Helle, World! -
Использование метода
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!