Ruby“each”块中的对象类型

时间:2012-01-02 01:49:12

标签: ruby

我正在做一个小应用程序从XML Feed中下载种子。

我能够解析XML文件,但是我对数组有点问题。

我创建了一个数组,其中包含我要下载的种子的链接并进行迭代。但是,在each块内,该项不是String。 Ruby说对象的类型是Array。

一些代码片段:

series = ['Fringe', 'Supernatural', 
          'The.Walking.Dead', 'Dexter', 
          'Game.of.Thrones', 'Merlin.2008']
links = ['http://torrentday.com/asdada/asdad/torrent',
         'http://torrentday.com/t5terter/Fringe.s08e02.torrent']
links.each do |link|
  series.each do |serie|
    if link.include? serie # doesn't work, because the type 
                           # of link is Array, not String.
      downloader.download(link)
      break
    end
  end
end

1 个答案:

答案 0 :(得分:2)

您的代码似乎对我有用:

> series = ['Fringe', 'Supernatural', 
*           'The.Walking.Dead', 'Dexter', 
*           'Game.of.Thrones', 'Merlin.2008']
=> ["Fringe", "Supernatural", "The.Walking.Dead", "Dexter", "Game.of.Thrones", "Merlin.2008"]
> links = ['http://torrentday.com/asdada/asdad/torrent',
*          'http://torrentday.com/t5terter/Fringe.s08e02.torrent']
=> ["http://torrentday.com/asdada/asdad/torrent", "http://torrentday.com/t5terter/Fringe.s08e02.torrent"]
> links.each do |link|
*   series.each do |serie|
*     if link.include? serie # doesn't work, because the type 
>       puts "#{link} included #{serie}"
>     end
>   end
> end
http://torrentday.com/t5terter/Fringe.s08e02.torrent included Fringe
=> ["http://torrentday.com/asdada/asdad/torrent", "http://torrentday.com/t5terter/Fringe.s08e02.torrent"]

它为ifserie的一个匹配组合正确执行了link语句的正文。