To remove special characters from a string in Ruby, you can use the gsub() method with a regular expression pattern.
In this example,
str1
with a value of "Hello! World!"
.gsub()
method with a regular expression pattern /[^a-zA-Z0-9 ]/
to replace all non-alphanumeric characters and spaces with an empty string.str1
.str1 = "Hello! World!"
str1 = str1.gsub(/[^a-zA-Z0-9 ]/, '')
puts "Modified string: #{str1}"
Modified string: Hello World
In this example,
str2
with a value of "apple@banana"
.gsub()
method with a regular expression pattern /[^a-zA-Z0-9 ]/
to replace all non-alphanumeric characters and spaces with an empty string.str2
.str2 = "apple@banana"
str2 = str2.gsub(/[^a-zA-Z0-9 ]/, '')
puts "Modified string: #{str2}"
Modified string: applebanana
In this tutorial, we learned How to Remove Special Characters from a String in Ruby language with well detailed examples.