I have a heredoc where I am using #{} to interpolate some other strings, but there is an instance where I also want to write the actual text #{some_ruby_stuff} in my heredoc, WITHOUT it being interpolated. Is there a way to escape the #{.
I've tried "\", but no luck. Although it escapes the #{}, it also includes the "\":
>> <<-END
#{RAILS_ENV} \#{RAILS_ENV}
END
=> " development \#{RAILS_ENV}\n"
For heredoc without having to hand-escape all your potential interpolations, you can use single-quote-style-heredoc. It works like this:
item = <<-'END'
#{code} stuff
whatever i want to say #{here}
END
I think the backslash-hash is just Ruby being helpful in some irb-only way.
>> a,b = 1,2 #=> [1, 2]
>> s = "#{a} \#{b}" #=> "1 \#{b}"
>> puts s #=> 1 #{b}
>> s.size #=> 6
So I think you already have the correct answer.
You can use ' quotes instead. Anything enclosed in them is not being interpolated.
Your solution with escaping # also works for me. Indeed Ruby interpreter shows
=> "\#{anything}"
but
> puts "\#{anything}"
#{anything}
=> nil
Your string includes exactly what you wanted, only p method shows it with escape characters. Actually, p method shows you, how string should be written to get exactly object represented by its parameter.
Related
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"
I'm trying to write a very simple regex to find all words in a string that start with the symbol #. Then change the word to a link. Like you would see in a Twitter where you can mention other usernames.
So far I have written this
def username_link(s)
s.gsub(/\#\w+/, "<a href='/username'>username</a>").html_safe
end
I know it's very basic and not much, but I'd rather write it on my own right now, to fully understand it, before searching GitHub to find a more complex one.
What I'm trying to find out is how can I reference that matched word and include it in the place of username. Once I can do that i can easily strip the first character, #, out of it.
Thanks.
You can capture using parentheses and backreference with \1 (and \2, and so on):
def username_link(s)
s.gsub(/#(\w+)/, "<a href='/\\1'>\\1</a>").html_safe
end
See also this answer
You should use gsub with back references:
str = "I know it's very basic and not much, but #tim I'd rather write it on my own."
def username_to_link(str)
str.gsub(/\#(\w+)/, '#\1')
end
puts username_to_link(str)
#=> I know it's very basic and not much, but #tim I'd rather write it on my own.
Following Regex should handle corner cases which other answers ignore
def auto_username_link(s)
s.gsub(/(^|\s)\#(\w+)($|\s)/, "\\1<a href='/\\2'>\\2</a>\\3").html_safe
end
It should ignore strings like "someone#company" or "#username-1" while converting everything like "Hello #username rest of message"
How about this:
def convert_names_to_links(str)
str = " " + str
result = str.gsub(
/
(?<=\W) #Look for a non-word character(space/punctuation/etc.) preceeding
# #an "#" character, followed by
(\w+) #a word character, one or more times
/xm, #Standard normalizing flags
'#\1'
)
result[1..-1]
end
my_str = "#tim #tim #tim, ##tim,#tim t#mmy?"
puts convert_names_to_links(my_str)
--output:--
#tim #tim #tim, ##tim,#tim t#mmy?
How to check whether a string contains special character in ruby. If I get regular expression also it is fine.
Please let me know
Use str.include?.
Returns true if str contains the given string or character.
"hello".include? "lo" #=> true
"hello".include? "ol" #=> false
"hello".include? ?h #=> true
special = "?<>',?[]}{=-)(*&^%$#`~{}"
regex = /[#{special.gsub(/./){|char| "\\#{char}"}}]/
You can then use the regex to test if a string contains the special character:
if some_string =~ regex
This looks a bit complicated: what's going on in this bit
special.gsub(/./){|char| "\\#{char}"}
is to turn this
"?<>',?[]}{=-)(*&^%$#`~{}"
into this:
"\\?\\<\\>\\'\\,\\?\\[\\]\\}\\{\\=\\-\\)\\(\\*\\&\\^\\%\\$\\#\\`\\~\\{\\}"
Which is every character in special, escaped with a \ (which itself is escaped in the string, ie \\ not \). This is then used to build a regex like this:
/[<every character in special, escaped>]/
"foobar".include?('a')
# => true
Why not use inverse of [:alnum:] posix.
Here [:alnum:] includes all 0-9, a-z, A-Z.
Read more here.
"Hel#lo".index( /[^[:alnum:]]/ )
This will return nil in case you do not have any special character and hence eaiest way I think.
How about this command in Ruby 2.0.0 and above?
def check_for_a_special_charachter(string)
/\W/ === string
end
Therefore, with:
!"He#llo"[/\W/].nil? => True
!"Hello"[/\W/].nil? => False
if you looking for a particular character, you can make a range of characters that you want to include and check if what you consider to be a special character is not part of that arsenal
puts String([*"a".."z"].join).include? "a" #true
puts String([*"a".."z"].join).include? "$" #false
I think this is flexible because here you are not limited as to what should be excluded
puts String([*"a".."z",*0..9,' '].join).include? " " #true
given a string as follow:
randomstring1-randomstring2-3df83eeff2
How can I use a ruby regex or some other ruby/rails friendly method to find everything up until the first dash -
In the example above that would be: randomstring1
Thanks
You can use this pattern: ^[^\-]*
mystring = "randomstring1-randomstring2-3df83eeff2"
firstPart = mystring[0, mystring.index("-")]
Otherwise, I think the best regex is #polishchuk's.
It matches from the beginning of the string, matches as many as possible of anything that is not a dash -.
Using irb you can do this too:
>> a= "randomstring1-randomstring2-3df83eeff2"
=> "randomstring1-randomstring2-3df83eeff2"
>> a.split('-').first
=> "randomstring1"
>>
For this situation, the index solution given by agent-j is probably better. If you did want to use regular expressions, the following non-greedy (specified by the ?) regex would grab it:
(^.*?)-
You can see it in Rubular.
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