replace a character in a string in ruby

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.rb
str = "hello world"
new_str = str.gsub("o", "a")
puts new_str  # => "hella warld"
82 chars
4 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.rb
str = "hello world"
new_str = str.sub("o", "a")
puts new_str  # => "hella world"
81 chars
4 lines

In this example, only the first occurrence of the character "o" is replaced with "a", resulting in the string "hella world".

related categories

gistlibby LogSnag