OneBite.Dev - Coding blog in a bite size

remove a character from a string in Ruby

Code snippet on how to remove a character from a string in Ruby

str = "Hello World"
str = str.chars.reject {|char| char == "o"}.join

This code snippet demonstrates how to remove a character from a string in Ruby. The first line assigns the string “Hello World” to the variable str. The second line then uses the String#chars method to convert the string into an array of characters. The Array#reject method is then used to remove the specified character - in this case, the letter “o” - and create a new array without that element. Finally, the Array#join method transforms the array back into a string without the unwanted character, and is assigned to the same variable str, overwriting the original string.

ruby