To keep only alphabets in a string in Ruby, you can use regular expressions or the 'gsub' method to remove non-alphabetic characters.
In this example,
str1
with a value of "Hello123 World"
.gsub
method with a regular expression /[^A-Za-z]/
to replace non-alphabetic characters with an empty string.result1
.result1
.str1 = "Hello123 World"
result1 = str1.gsub(/[^A-Za-z]/, '')
puts "Modified string: #{result1}"
Modified string: HelloWorld
In this example,
str2
with a value of "apple@banana"
.gsub
method with a regular expression /[^A-Za-z]/
to replace non-alphabetic characters with an empty string.result2
.result2
.str2 = "apple@banana"
result2 = str2.gsub(/[^A-Za-z]/, '')
puts "Modified string: #{result2}"
Modified string: applebanana
In this tutorial, we learned How to keep only Alphabets in a String in Ruby language with well detailed examples.