I have someone entering a form with some string input. What I need to do is replace any white space in the string with " AND " (no quotes). What's the best way to do this?
Also, how would I go about doing this if I wanted to remove all the whitespace in the string?
Thanks
to replace with and:
s = 'this has some whitespace'
s.gsub! /\s+/, ' AND '
=> "this AND has AND some AND whitespace"
to remove altogether:
s = 'this has some whitespace'
s.gsub! /\s+/, ''
=> "thishassomewhitespace"
Split and join is another technique:
s = " a b c "
s.split(' ').join(' AND ')
# => "a AND b AND c"
This has the advantage of ignoring leading and trailing whitespace that Peter's RE does not:
s = " a b c "
s.gsub /\s+/, ' AND '
# => " AND a AND b AND c AND "
Removing whitespace
s.split(' ').join('')
# or
s.delete(' ') # only deletes space chars
use gsub method for replacing whitespace
s = "ajeet soni"
=> "ajeet soni"
s.gsub(" "," AND ")
=> "ajeet AND soni"
Related
# code
ENV['VAR_1'] = 'HELLO 1'
ENV['VAR_2'] = 'HELLO 2'
ENV['VAR_3'] = 'HELLO 3'
# code
How do I extract using ruby and regex each variable and it's value?
Currently I'm doing line by line which is stupid.
S3_SECRET = line.split(' = ').last.delete("'") if line =~ /ENV\['S3_SECRET'\]/
S3_KEY = line.split(' = ').last.delete("'") if line =~ /ENV\['S3_KEY'\]/
S3_BUCKET = line.split(' = ').last.delete("'") if line =~ /ENV\['S3_BUCKET'\]/
You may have quite a verbose regex like
/^ENV\['(.*?)'\] *= *'(.*?)'$/
See the regex demo.
Details:
^ - start of line
ENV\[' - a literal ENV[' substring
(.*?) - Group 1 capturing 0+ chars other than a newline as few as possible up to the first
'\] - literal '] text
*= * - a = sign enclosed with optional (0 or more) spaces
' - a single quote
(.*?) - Group 2 capturing 0+ chars other than a newline as few as possible up to the
' - final ' at...
$ - the end of the line.
Here is a Ruby demo:
s = <<DATA
# code
ENV['VAR_1'] = 'HELLO 1'
ENV['VAR_2'] = 'HELLO 2'
ENV['VAR_3'] = 'HELLO 3'
# code
DATA
puts s.scan(/^ENV\['(.*?)'\] *= *'(.*?)'$/).to_h
Output: {"VAR_1"=>"HELLO 1", "VAR_2"=>"HELLO 2", "VAR_3"=>"HELLO 3"}
Suppose you've read the file into an array of lines (using, say, IO#readlines).
arr = ["ENV['VAR_1'] = 'HELLO 1'",
"ENV['VAR_2'] = 'HELLO 2'",
"ENV['VAR_3'] = 'HELLO 3'"]
Rather than using a complex regex straight away, we can remove the text we don't want, split the slimed-down strings on "=", surrounded by spaces, and then convert the resultant array to a hash.
bad_bits = %w| ENV[ ] ' |
#=> ["ENV[", "]", "'"]
r = Regexp.union(bad_bits)
#=> /ENV\[|\]|'/
arr.map { |str| str.gsub(r, '') }.map { |s| s.split(/\s+=\s+/) }.to_h
#=> {"VAR_1"=>"HELLO 1", "VAR_2"=>"HELLO 2", "VAR_3"=>"HELLO 3"}
Notice that Regexp::union does the escaping of regex's special characters for you.
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..
You can also use .tr method.
str = "\"hai"
str = str.tr('\"', '')
##OR
str.tr!('\"', '')
## OUTPUT
"hai"
You can pass a regex instead, try this
str = "\"hai"
str = str.gsub(/\"/, '')
Hope that helps!
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.
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 ('"').
I could easily strip white space in the left side of a normal string like this:
" Remove whitespace".lstrip #=> "Remove whitespace"
But if the string contains HTML I am not able to do it:
#html_str = "<p> Remove whitespace </p>"
#html_safe_str = #html_str.html_safe #=> " Remove whitespace"
#html_safe_str.lstrip #=> "<p> Remove whitespace</p>"
#html_str.html_safe.lstrip is not working.
I dont want to remove all the s in the string. I want to remove all the s immediately after the opening <p> tag
Expected result: "Remove whitespace "
How is it possible?
In Rails 4, strip_tags has been combined with gsub. You can use gsub to remove s. Then, you need to use sanitizer method provided by ActionView:
#html_str = "<p> Remove whitespace </p>"
str = #html_str.gsub(/<p>\s*( \s*)+/, "<p>")
ActionView::Base.full_sanitizer.sanitize(str).lstrip # => "Remove whitespace "
It will work for Rails 3 as well as Rails 4.
You can do like this:
#html_str = "<p> Remove whitespace</p>"
#html_str = #html_str.gsub(" ", "") => "<p> Remove whitespace</p>"
#html_str1 = ActionController::Base.helpers.strip_tags(#html_str) => " Remove whitespace" #if you are doing this at controller level
#html_str1 = strip_tags(#html_str) => " Remove whitespace" #if you are doing this at view level
#now at the last
#html_str2 = #html_str1.strip => "Remove whitespace"
Shortly:
#html_str = "<p> Remove whitespace</p>"
#html_str1 = ActionController::Base.helpers.strip_tags(#html_str.gsub(" ", "")).strip => "Remove whitespace"
Hope this will work for you
If html_safe converts 's to white spaces, you can try:
#html_str.html_safe.lstrip
Hope that helps!
You can use gsub for that
#html_str = "<p> Remove whitespace</p>"
#html_str = #html_str.gsub(" ", "")
#html_safe_str = #html_str.html_safe
or
If you completely want to remove tags then as Andrey suggested, you can use strip_tags, but to use it in controller you need to call using ActionController::Base
#html_str = ActionController::Base.helpers.strip_tags("<p> Remove whitespace</p>").gsub(" ", "").lstrip
It will output : Remove whitespace
Hope this helps!
You can do it like this:
ActionController::Base.helpers.strip_tags(#html_str.html_safe).gsub(" ","").lstrip
# => "Remove whitespace"
I'm trying to have greentext support for my Rails imageboard (though it should be mentioned that this is strictly a Ruby problem, not a Rails problem)
basically, what my code does is:
1. chop up a post, line by line
2. look at the first character of each line. if it's a ">", start the greentexting
3. at the end of the line, close the greentexting
4. piece the lines back together
My code looks like this:
def filter_comment(c) #use for both OP's and comments
c1 = c.content
str1 = '<p class = "unkfunc">' #open greentext
str2 = '</p>' #close greentext
if c1 != nil
arr_lines = c1.split('\n') #split the text into lines
arr_lines.each do |a|
if a[0] == ">"
a.insert(0, str1) #add the greentext tag
a << str2 #close the greentext tag
end
end
c1 = ""
arr_lines.each do |a|
strtmp = '\n'
if arr_lines.index(a) == (arr_lines.size - 1) #recombine the lines into text
strtmp = ""
end
c1 += a + strtmp
end
c2 = c1.gsub("\n", '<br/>').html_safe
end
But for some reason, it isn't working! I'm having weird things where greentexting only works on the first line, and if you have greentext on the first line, normal text doesn't work on the second line!
Side note, may be your problem, without getting too in depth...
Try joining your array back together with join()
c1 = arr_lines.join('\n')
I think the problem lies with the spliting the lines in array.
names = "Alice \n Bob \n Eve"
names_a = names.split('\n')
=> ["Alice \n Bob \n Eve"]
Note the the string was not splited when \n was encountered.
Now lets try this
names = "Alice \n Bob \n Eve"
names_a = names.split(/\n/)
=> ["Alice ", " Bob ", " Eve"]
or This "\n" in double quotes. (thanks to Eric's Comment)
names = "Alice \n Bob \n Eve"
names_a = names.split("\n")
=> ["Alice ", " Bob ", " Eve"]
This got split in array. now you can check and append the data you want
May be this is what you want.
def filter_comment(c) #use for both OP's and comments
c1 = c.content
str1 = '<p class = "unkfunc">' #open greentext
str2 = '</p>' #close greentext
if c1 != nil
arr_lines = c1.split(/\n/) #split the text into lines
arr_lines.each do |a|
if a[0] == ">"
a.insert(0, str1) #add the greentext tag
# Use a.insert id you want the existing ">" appended to it <p class = "unkfunc">>
# Or else just assign a[0] = str1
a << str2 #close the greentext tag
end
end
c1 = arr_lines.join('<br/>')
c2 = c1.html_safe
end
Hope this helps..!!
I'm suspecting that your problem is with your CSS (or maybe HTML), not the Ruby. Did the resulting HTML look correct to you?
In Ruby on Rails,I got a string number is made of 3 parts : prefix , counter , suffix
In model Setup:
def self.number
prefix = setup.receipt_prefix.blank? ? "" : setup.receipt_prefix.to_s
counter = setup.receipt_counter.blank? ? "" : setup.receipt_counter+1
suffix = setup.receipt_suffix.blank? ? "" : setup.receipt_suffix.to_s
each individual string shows fine:
puts prefix
=> \#_
puts counter
=>
1234
puts suffix
=>
#$#s
but when I add 3 string together, an addition back slash appear :
prefix + counter + suffix
=>
\\#_1234\#$#s
how can I escape "#" "\" when I add 3 string together ? like
=>
\#_1234#$#s
any Ruby or Rails's helper I can use in the model?
thx~~
The string will look different if you get the value versus print (puts) it out. See the following irb session.
>> a = "\\#_"
=> "\\#_"
>> puts a
\#_
=> nil
>> b = "1234"
=> "1234"
>> puts a + b
\#_1234
=> nil
>> a + b
=> "\\#_1234"
The actual string value has two backslashes in it. But only one shows up if you print the string.