如何从字符串中剥离URL并将其放置为数组?

Zac*_*iro 0 ruby arrays url loops ruby-on-rails

我正在构建一个小脚本,用于搜索服务推文的5张最新图片,隔离URL并将该URL放入数组中.

def grabTweets(linkArray) #brings in empty array
  tweets = Twitter.search("[pic] "+" url.com/r/", :rpp => 2, :result_type => "recent").map do |status|
  tweets = "#{status.text}" #class = string

  url_regexp = /http:\/\/\w/ #isolates link
  url = tweets.split.grep(url_regexp).to_s #chops off link, turns link to string from an array

  #add link to url array
  #print linkArray #prints []

  linkArray.push(url)
  print linkArray

  end
end

x = []
timelineTweets = grabTweets(x)
Run Code Online (Sandbox Code Playgroud)

该函数返回如下内容:["[\"http://t.co/6789 \"]"] ["[\"http://t.co/12345 \"]"]

我试图让它返回["http://t.co/6789","http://t.co/1245"],但它没有管理它.

任何帮助在这里将不胜感激.我不确定我做错了什么.

the*_*Man 5

在Ruby中获取URL的最简单方法是使用该URI::extract方法.这是一个预先存在的轮子工作:

require 'uri'
require 'open-uri'

body = open('http://www.example.com').read

urls = URI::extract(body)
puts urls
Run Code Online (Sandbox Code Playgroud)

哪个回报:

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
http://www.w3.org/1999/xhtml
http://www.icann.org/
mailto:iana@iana.org?subject=General%20website%20feedback
Run Code Online (Sandbox Code Playgroud)

获得阵列后,您可以根据需要进行过滤,也可以为其提供一个要提取的方案列表.