To replace a character/substring in a string in Ruby, you can use the gsub
(global substitution) or sub
(substitution) methods of the String
class.
The gsub
method replaces all occurrences of a pattern with a given string, while sub
replaces only the first occurrence.
Here's an example of how to use gsub
to replace all occurrences of a character in a string:
main.rb82 chars4 lines
In this example, all occurrences of the character "o" in the string "hello world" are replaced with "a", resulting in the string "hella warld".
Similarly, you can use sub
to replace only the first occurrence of a character:
main.rb81 chars4 lines
In this example, only the first occurrence of the character "o" is replaced with "a", resulting in the string "hella world".
gistlibby LogSnag