kelvin
kelvin

Reputation: 179

Removing leading and trailing double quotes in string in rails

I want to trim the leading and trailing quotes of a string without any replacement.. I have tried with gsub.. but nothing helped.. I want to achieve something like., "hai" to hai

In Java, I ll use like the following.,

String a="\"hai";
String z=a.replace("\"", "");
System.out.println(z);

Output:

hai

How can I achieve this in rails? Kindly pls help..

In my irb

2.2.3 :008 > str = "\"hai"
  => "\"hai"
2.2.3 :009 > str.tr!('\"', '')
  => "hai"

Why am I not able to get output without double quotes?? Sorry ., If my question doesn't meet your standard..

Upvotes: 0

Views: 2879

Answers (4)

Amit Sharma
Amit Sharma

Reputation: 3477

You can also use .tr method.

str = "\"hai"
str = str.tr('\"', '')

##OR

str.tr!('\"', '')

## OUTPUT
"hai"

Upvotes: 1

tbreier
tbreier

Reputation: 214

This should work:

str = "\"hai"
str.tr('"', '')

Note that you only escape (\") double-quotes in a string that is defined using double-quotes ("\""), otherwise, you don't ('"').

Upvotes: 0

guitarman
guitarman

Reputation: 3310

This removes the leading and trailing double quotes from the string only. You get a new string and keep the old one.

str = "\"ha\"i\""
# => "\"ha\"i\""
new_str = str.gsub(/^"+|"+$/, '')
# => "ha\"i"

str
# => "\"ha\"i\""

Or you change the original string.

str.gsub!(/^"+|"+$/, '')
# => "ha\"i"
str
# => "ha\"i"

That's a ruby convention. Method names with an exclamation mark/point modify the object itself.

Upvotes: 0

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You can pass a regex instead, try this

str = "\"hai"
str = str.gsub(/\"/, '')

Hope that helps!

Upvotes: 0

Related Questions