How to remove double quotes from String in Ruby?
In this article, we will discuss how to remove double quotes from a string using Ruby. We can remove double quotes from strings through different methods ranging from using gsub
Method with Regular Expression to delete
Method
Table of Content
- Removing double quotes from string using gsub Method with Regular Expression
- Removing double quotes from string using delete Method
- Removing double quotes from string using tr Method
Removing double quotes from string using gsub Method with Regular Expression
The gsub
method replaces all occurrences of double quotes with an empty string
Syntax:
string.gsub(/”/, ”)
Example: In this example, we use gsub
method with a regular expression /"/
to remove all occurrences of double quotes from the string.
# Example string with double quotes
string = '"Hello, World!"'
# Remove double quotes using gsub method
result = string.gsub(/"/, '')
# Output the result
puts "String without double quotes: #{result}" # Output: String without double quotes: Hello, World!
Output
true false
Removing double quotes from string using delete Method
The delete method deletes specified characters from the string and here we use it to remove double quotes from the string
Syntax:
string.delete(‘”‘)
Example: In this example, we use delete
method to remove all occurrences of double quotes from the string.
# Example string with double quotes
string = '"Hello, World!"'
# Remove double quotes using delete method
result = string.delete('"')
# Output the result
puts "String without double quotes: #{result}" # Output: String without double quotes: Hello, World!
Output
true false
Removing double quotes from string using tr Method
The tr method translates characters in the string thus removing the double quotes from staring
Syntax:
string.tr(‘”‘, ”)
Example: In this example we use the tr
method to remove all occurrences of double quotes from the string.
# Example string with double quotes
string = '"Hello, World!"'
# Remove double quotes using tr method
result = string.tr('"', '')
# Output the result
puts "String without double quotes: #{result}" # Output: String without double quotes: Hello, World!
Output
true false
Contact Us