remove a character from a string in ruby

To remove a specific character from a string in Ruby, there are various methods available. Here are a few examples:

  1. Using the delete method:
main.rb
my_string = "hello world"
my_string.delete!("l")
puts my_string # "heo word"
77 chars
4 lines
  1. Using the gsub method:
main.rb
my_string = "hello world"
my_string = my_string.gsub("l", "")
puts my_string # "heo word"
90 chars
4 lines
  1. Using the tr method:
main.rb
my_string = "hello world"
my_string = my_string.tr("l", "")
puts my_string # "heo word"
88 chars
4 lines

Note that these methods will remove all occurrences of the specified character. If you only want to remove the first occurrence, you can use the sub method instead of gsub or add an optional parameter to delete or tr to limit the number of replacements:

main.rb
my_string = "hello world"
my_string.sub!("l", "") # removes only the first occurrence
puts my_string # "helo world"

my_string = "hello world"
my_string.delete!("l", 1) # removes only one "l"
puts my_string # "heo world"

my_string = "hello world"
my_string.tr!("l", "", 1) # removes only one "l"
puts my_string # "heo world"
326 chars
12 lines

gistlibby LogSnag