Dheena
Dheena

Reputation: 117

How to gsub slash (/) to "" in ruby

To gsub / to "" ruby

I tried as,

ss = "http://url.com/?code=\#{code}"

I am fetching this url from database then have to gsub \ to '' to pass the dynamic value in code

How to gsub \ to ''

required output

ss = "http://url.com/?code=#{code}"

Upvotes: 0

Views: 652

Answers (3)

Rajnish Mishra
Rajnish Mishra

Reputation: 27

You can try in this way also, working fine for my case.

  url = 'www.abc.com?user_id=#{user[:id]}'

  uri = URI.parse(url.gsub("=\#", "="))

  uri.query = URI.encode_www_form({user_id: 12})

  puts uri.to_s ==> "www.abc.com?user_id=12"

Upvotes: -1

user513951
user513951

Reputation: 13612

I believe what you may be asking is "how do I force Ruby to evaluate string interpolation when the interpolation pattern has been escaped?" In that case, you can do this:

eval("\"#{ss}\"")

If this is what you are attempting to do, though, I would highly discourage you. You should not store strings containing the literal characters #{ } in your database fields. Instead, use %s and then sprintf the values into them:

# Stored db value
ss = "http://url.com/?code=%s"

# Replace `%s` with value of `code` variable
result = sprintf(ss, code)

If you only need to know how to remove \ from your string, though, you can represent a \ in a String or Regexp literal by escaping it with another \.

ss.gsub(/\\/,'')

Upvotes: 1

Carlos Baraza
Carlos Baraza

Reputation: 60

Your problem is actually not a problem. When you write "http://url.com/?code=\#{code}" in ruby, \# means that ruby is escaping the # character, cause # is a protected character. So you should have the backslash to escape it.

Just to prove this, if you write in a console your string with single quotes (single quotes will escape any special character (but single quotes, of course)):

>> 'http://url.com/?code=#{code}'
=> "http://url.com/?code=\#{code}"

This may be a little obscure but, if you want to evaluate the parameter code in the string, you could do something like this:

>> code = 'my_code'
>> eval("\"http://url.com/?code=\#{code}\"")
=> "http://url.com/?code=my_code"

Upvotes: 2

Related Questions