Question

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 > 
Was it helpful?

Solution 2

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

OTHER TIPS

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 /.

You can gsub all \ by doing:

your_string.gsub('\','')
data.grep(/http/){|x|x.delete '\\\" '}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top