清理阵列中的href

时间:2016-06-23 12:37:37

标签: ruby-on-rails arrays ruby gsub code-cleanup

我在数组中存储了一系列href,我想清理它们,以便只留下链接或者取出撇号。有人能帮助我以这种方式清理阵列吗?

以下是数组中的一个摘录,用于提供存储内容的示例

<a href="http://www.abdn.ac.uk/study/courses/undergraduate/B9C7/">View course details on provider's website</a>

这可能是用gsub完成的,如果是的话,怎么做?

编辑包括: 我通过抓取数据创建了如下数组:

def process_course_details(course_details)
    details_array =[]
    details_link = true 
    entry_link = true

            details_info = {}
            # Sets all data in hash
            @details_url = course_details.search('div.coursedetails_programmeurl a')
            @details_url.map{ |link| link[/href="([^"]*)"/, 1]} 
            details_info[:url]          = @details_url

            details_array.push(details_info)
            print_details_info(details_info)


         entry_link = course_details.search('ul.details_tabs a').first
         if entry_link

             details_info[:entry] = process_entry(@mechanize.get(entry_link["href"]))
         end 

 end

2 个答案:

答案 0 :(得分:1)

▶ str = %|<a href="http://www.abdn.ac.uk/study/courses/undergraduate/B9C7/">View course details on provider's website</a>| # c'mon, SO’s parser
▶ str[/<a.+href="(.*?)"/, 1]
#⇒ "http://www.abdn.ac.uk/study/courses/undergraduate/B9C7/"

对于字符串数组:

▶ arr = [str] * 3
▶ arr.map { |s| s[/<a.+href="(.*?)"/, 1] }

答案 1 :(得分:0)

解析整个数组:

Array(@details_url).map{ |link| link.innert_html[/href="([^"]*)"/, 1] }

您可以在Rubular主页上试用正则表达式。