2

How to remove all \ elements from the array?

Array of size 6:

data =
[
      " \"\"http://www.web1.com\\\"",
      "\"",
      " \"\"https://www.web2.com\\\"",
      "\"",
      " \"\"http://www.web3.com\\\"",
      "\"",
 ]

desired:

 ["www.web1.com", "www.web2.com", "www.web3.com"]

tried :

 data = 
 => [" \"\"http://www.web1.com\\\"", "\"", " \"\"https://www.web2.com\\\"", "\"", " \"\"http://www.web3.com\\\"", "\""] 
2.0.0-p353 :019 > data.each do |d| 
2.0.0-p353 :020 >     d.gsub!(/\+/,'')
2.0.0-p353 :021?>   end
 => [" \"\"http://www.web1.com\\\"", "\"", " \"\"https://www.web2.com\\\"", "\"", " \"\"http://www.web3.com\\\"", "\""] 
2.0.0-p353 :022 > 

4 Answers 4

2

Here is how you can get your desired output:

data.map { |e| e.gsub(/["\s\\\/]|(?:https?:\/\/)/,'') }.reject(&:empty?)

You iterate over data array and substitute element's contents that match regexp with ''. Then you just drop empty strings.

Let me explain the regexp a little: [...] means group of characters, we will match any character from a group; | is or operator; (?:) is non-capuring group, so we must match whole https:// or http://; \s means any whitespace character; \\ and \/ are escaped \ and /.

Sign up to request clarification or add additional context in comments.

4 Comments

Sure, hope that helps.
you can replace select{|e| !e.empty?} with reject{|e| e.empty?}
@Kavu What about a url like http://www.htps.com/ or anything else which has htps char in the domain part :)
@xdazz yeah, it will totally fail :-D Need to improve my answer.
1

This will give you the result you expected.

data.grep(/https?:\/\/([^\\]*)/) {|v| v.match(/https?:\/\/([^\\]*)/)[1] }

But you have to know that \ is used to escape the special char in the string.

"\\" has only one char that is \, "\"" has only one char that is ".

Comments

0

You can gsub all \ by doing:

your_string.gsub('\','')

Comments

0
data.grep(/http/){|x|x.delete '\\\" '}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.