How to gsub slash (/) to "" in ruby - ruby-on-rails

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}"

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"

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(/\\/,'')

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"

Related

Single quote string string interpolation

I am trying to set an email address within ActionMailer with Rails. Before it was hard coded, but we want to make them ENV variables now so we don't need to amend code each time an email changes.
Here is how it's currently defined:
from = '"Name of Person" <email#email.com>'
I've tried setting the email as an environment variable using ENV['EMAIL'] but I'm having no luck even with #{ENV['EMAIL'}.
Can anyone point me in the right direction?
You cannot use string interpolation with single-quoted strings in Ruby.
But double-quoted strings can!
from = "'Name of Person' <#{ENV['EMAIL']}>"
But if you want to keep your double-quotes wrapping the Name of Person, you can escape them with a backslash \:
from = "\"Name of Person\" <#{ENV['EMAIL']}>"
Or use string concatenation:
from = '"Name of Person" <' + ENV['EMAIL'] + '>'
# but I find it ugly
If you want to embed double quotes in an interpolated string you can use % notation delimiters (which Ruby stole from Perl), e.g.
from = %|"Name of Person", <#{ENV['EMAIL']}>|
or
from = %("Name of Person", <#{ENV['EMAIL']}>)
Just pick a delimiter after the % that isn't already in your string.
You can also use format. I have not seen it used as commonly in Ruby as in other languages (e.g. C, Python), but it works just as well:
from = format('"Name of Person", <%s>', ENV["EMAIL"])
Alternative syntax using the % operator:
from = '"Name of Person", <%s>' % ENV["EMAIL"]
Here is the documentation for format (aka sprintf):
http://ruby-doc.org/core-2.2.0/Kernel.html#method-i-format

How to define a ruby array that contains a backslash("\") character?

I want to define an array in ruby in following manner
A = ["\"]
I am stuck here for hours now. Tried several possible combinations of single and double quotes, forward and backward slashes. Alas !!
I have seen this link as well : here
But couldn't understand how to resolve my problem.
Apart from this what I need to do is -
1. Read a file character by character (which I managed to do !)
2. This file contains a "\" character
3. I want to do something if my array A includes this backslash
A.includes?("\")
Any help appreciated !
There are some characters which are special and need to be escaped.
Like when you define a string
str = " this is test string \
and this contains multiline data \
do you understand the backslash meaning here \
it is being used to denote the continuation of line"
In a string defined in a double quotes "", if you need to have a double quote how would you doo that? "\"", this is why when you put a backslash in a string you are telling interpretor you are going to use some special characters and which are escaped by backslash. So when you read a "\" from a file it will be read as "\" this into a ruby string.
char = "\\"
char.length # => 1
I hope this helps ;)
Your issue is not with Array, your question really involves escape sequences for special characters in strings. As the \ character is special, you need to first prepend it (escape it) with a leading backslash, like so.
"\\"
You should also re-read your link and the section on escape sequences.
You can escape backslash with a backslash in double quotes like:
["\\"].include?("\\")

Why doesn't this regex match in ruby but matches in any other language?

The following works on Rubular.com but doesn't seem to match in ruby:
The string:
str = "<em>really</em>inexpensive"
Objective:
Add a space after any closing tag without any space after it.
The regex:
str.gsub("/(<\/[a-zA-Z]+>)(\S)/","\1 \2")
It should give back "<em>really</em> inexpensive"
You should use regular expression literal (/.../), not string ("..."). And escape the \ in the replacement string. (I used single-quote version of string in the following example)
str = "<em>really</em>inexpensive"
str.gsub(/(<\/[a-zA-Z]+>)(\S)/, '\1 \2') # '\1 \2' == "\\1 \\2"
# => "<em>really</em> inexpensive"

Non-regexp version of gsub in Ruby

I am looking for a version of gsub which doesn't try to interpret its input as regular expressions and uses normal C-like escaped strings.
Update
The question was initiated by a strange behavior:
text.gsub("pattern", "\\\\\\")
and
text.gsub("pattern", "\\\\\\\\")
are treated as the same, and
text.gsub("pattern", "\\\\")
is treated as single backslash.
There are two layers of escaping for the second parameter of gsub:
The first layer is Ruby string constant. If it is written like \\\\\\ it is unescaped by Ruby like \\\
the second layer is gsub itself: \\\ is treated like \\ + \
double backslash is resolved into single: \\ => \ and the single trailing backslash at the end is resolved as itself.
8 backslashes are parsed in the similar way:
"\\\\\\\\" => "\\\\"
and then
"\\\\" => "\\"
so the constants consisting of six and eight backslashes are resolved into two backslashes.
To make life a bit easier, a block may be used in gsub function. String constants in a block are passed only through Ruby layer (thanks to #Sorrow).
"foo\\bar".gsub("\\") {"\\\\"}
gsub accepts strings as first parameter:
the pattern is typically a Regexp; if given as
a String, any regular expression metacharacters
it contains will be interpreted literally
Example:
"hello world, i am thy code".gsub("o", "-foo-")
=> "hell-foo- w-foo-rld, i am thy c-foo-de"

How do you store a Ruby regex via a Rails controller?

For an admin function in a Rails app, I want to be able to store regexes in the DB (as strings), and add them via a standard controller action.
I've run into 2 issues:
1) The Rails parameter filters seem to be automatically escaping backslashes (escape characters), which messes up the regex. For instance:
\s{1,2}(foo)
becomes:
\\s{1,2}(foo)
2) So then I tried to use a write_attribute to gsub instances of double backslashes with single backslashes (essentially unescaping them). This proved to be much trickier than expected. (I'm using Ruby 1.9.2 if it matters). Some things I've found:
"hello\\world".gsub(/\\/, ' ') #=> "hello world"
"hello\\world".gsub(/\\/, "\\") #=> "hello\\world"
"hello\\world".gsub(/\\/, '\\') #=> "hello\\world"
What I'm trying to do is:
"hello\\world".gsub(/\\/, something) #=> "hello\world"
I'd love to know both solutions.
1) How can you safely pass and store regexes as params to a Rails controller action?
2) How can you substitute double backslashes with a single backslash?
In short, you can't substitute a double backslash with a single one in a string, because a single backslash in a string is an escape character. What you can do is the following:
Regexp.new("hello\\world") #=> /hello\world/
This will convert your string into a regular expression. So that means: store your regular expressions as strings (with the escaped characters) and convert them into regular expressions when you want to compare against them:
regexp = "\\s{1,2}(foo)"
reg = Regexp.new(regexp) #=> /\s{1,2}(foo)/
" foo" =~ reg #=> 0

Resources