Remove double backslash from string with Ruby - ruby-on-rails

I have the following string:
string = "\"2014\\/jul\\/grandes\\/volvo-s-60-d5-momentum-1403253_2.jpg\""
that I want to gsub into this string:
string = "2014/jul/grandes/volvo-s-60-d5-momentum-1403253_2.jpg"
Here is how I thought it should work:
string.gsub(/\\./,'')
but this returns:
"\"2014julgrandesvolvo-s-60-d5-momentum-1403253_3.jpg\""
What am I doing wrong?

You have a “dot” in regexp for no reason. Instead of:
string.gsub(/\\./,'')
try:
string.gsub(/["\\]/,'')
Or, credits to #sawa, try this instead:
string.tr('"\\','')
Or, credits to #Chirantan:
string.delete('"\\')
Benchmarks: http://gist.github.com/dominikh/208915

string.delete('\\\"')
is one possible solution. But I'm sure there are better ones out there.

Another nasty one using String#[]= method. This is just for fun :-
string[/["\\]/] = '' until string[/["\\]/].nil?
# or
string[/["\\]/] = '' while string =~ /["\\]/
But #gsub is better way to solve this. If you don't want to modify the original string, then use String#slice instead of String#[]=. That's it.

Related

Getting substring value in Chef ruby

I have a string that has the following value:
ucp-1.1.0_dtr-2.0.0
I am trying to fetch only 1.1.0 from the string. I am using the following code but it doesn't seem to work
substring = ucp-1.1.0_dtr-2.0.0.gsub('ucp-','')
String's [] and a simple regex will do it:
'ucp-1.1.0_dtr-2.0.0'[/[\d.]+/] # => "1.1.0"
This works because the search will stop as soon as it matches, so the first occurrence wins resulting in 1.1.0.
If you wanted the second/last occurrence then adding $ tells the regex engine to only look at the end of the line for the matching pattern:
'ucp-1.1.0_dtr-2.0.0'[/[\d.]+$/] # => "2.0.0"
The Regexp documentation covers all this.
substring = "ucp-1.1.0_dtr-2.0.0".gsub('ucp-','').split("_").first untried.
using regex with ruby string methods you can achieve this..
"ucp-1.1.0_dtr-2.0.0"
version = "ucp-1.1.0_dtr-2.0.0".scan(/[0-9_]/).join(".").split("_").first.slice(0..-2)
Or with your code you can try this..
substring = "ucp-1.1.0_dtr-2.0.0".gsub('ucp-','').split("_").first
Try this (verified):
"ucp-1.1.0_dtr-2.0.0".match(/^.-(.)_.-.$/)[1]

Ruby how to check if hash has a key that is a variable?

I have a Ruby hash that has attributes like this:
{:type=>"article", :id=>"207", :infographic=>nil, :guest_post=>nil, :interview=>nil}
Suppose I want to check if this hash has a key that is the same as a variable "keyVar"
keyVar = ":type"
If I do hash.has_key?(keyVar), it returns false, but it obviously does have the key.
What am I doing wrong?
Your keyVar variable is a string, not a symbol. Worse yet, it's a string with a prefixed colon, so it's not easily possible to convert it to a symbol.
What you want is
hash.has_key?(:type)
But what you're doing is:
hash.has_key?(":type")
Simpy using ":type".to_sym would get you :":type". You'll need something like this:
hash.has_key?(keyVar.gsub(":", "").to_sym)
You are checking for the wrong key. Do this:
key_var = :type
hash.key?(key_var)
If you happened to have the wrong key:
key_var = ":type"
then, the way to convert that to the correct key is:
key_var.delete(":").to_sym
so
hash.has_key?(key_var.delete(":").to_sym)
will work. Using gsub as another answer suggests is meaningless as there is only one : in the string. sub is better, but why use it when you can use delete?
there are many ways to check
> hash = {:type=>"article",
:id=>"207",
:infographic=>nil,
:guest_post=>nil,
:interview=>nil}
> hash.keys.include?(:type)
> true
> hash.has_key?(:type)
> true
> hash.key?(:type)
> true
and more.... Just read documentation

How can i get double quoted characters from a string in ruby on rails

If I have a string in a file:
str = hi "Sonal"
I am able to fetch this line of file in a string. Now I want to fetch the characters between the double quotes. i.e. Sonal. How can I do it in ruby?
try the following
'hi "Sonai"'.match(/"(?<inside_quote>.+)"/)[:inside_quote]
You can use regular expression like this,
given_string[/\".*\"/]
This will match the characters under quotes.
or without regexp try something like this s[s.index('"')..s.rindex('"')]

Ruby regex find and replace a number inside a string

How would I find and replace '49' when '49' will be an unknown id, using ruby on rails?
str = "select * from clients where client_id = 49 order by registration_date asc"
str = str.gsub(/someRegExThatFinds49/, replacement_id) # <------ Here's the concept
Looking for a syntax and example that's correct. Thanks.
This would work, using a copy of the string:
new_str = str.gsub(/\d+/, replacement_id)
Or, if you prefer to do it in place (modifying the string directly)
str.gsub!(/\d+/, replacement_id)
ian.
unknown_id = 49
puts "hello4849gone".gsub(/#{unknown_id}/, "HERE") #=> hello48HEREgone
str = str.gsub(/49/, replacement_id)
Or use the self-updating version:
str.gsub!(/49/, replacement_id)
Also, check out Rubular which allows you to test out regular expressions.

Ruby gsub function

I'm trying to create a BBcode [code] tag for my rails forum, and I have a problem with the expression:
param_string.gsub!( /\[code\](.*?)\[\/code\]/im, '<pre>\1</pre>' )
How do I get what the regex match returns (the text inbetween the [code][/code] tags), and escape all the html and some other characters in it?
I've tried this:
param_string.gsub!( /\[code\](.*?)\[\/code\]/im, '<pre>' + my_escape_function('\1') + '</pre>' )
but it didn't work. It just passes "\1" as a string to the function.
You should take care of the greedy behavior of the regular expressions. So the correct code looks like this:
html.gsub!(/\[(\S*?)\](.*?)\[\/\1\]/) { |m| escape_method($1, $2) }
The escape_method then looks like this:
def escape_method( type, string )
case type.downcase
when 'code'
"<pre>#{string}</pre>"
when 'bold'
"<b>#{string}</b>"
else
string
end
end
Someone here posted an answer, but they've deleted it.
I've tried their suggestion, and made it work with a small change. Whoever you are, thanks! :)
Here it is
param_string.gsub!( /\[code\](.*?)\[\/code\]/im ) {|s| '<pre>' + my_escape_function(s) + '</pre>' }
You can simply use "<pre>#{$1}</pre>" for your replacement value.

Resources