7

假设我有一个这样的数组:

["auburn", "http://auburn.craigslist.org/web/", "http://auburn.craigslist.org/cpg/", "http://auburn.craigslist.org/eng/", "http://auburn.craigslist.org/sof/", "http://auburn.craigslist.org/sad/"]

我想做的只是处理这个数组中的 URL——它总是从开始element[1]并上升。

我怎么做?

4

5 回答 5

13

这里只显示从 1 开始的元素(第二个元素),-1 代表最后一个元素

a = ["auburn", "http://auburn.craigslist.org/web/", "http://auburn.craigslist.org/cpg/", "http://auburn.craigslist.org/eng/", "http://auburn.craigslist.org/sof/", "http://auburn.craigslist.org/sad/"] 

p a[1..-1]
=> ["http://auburn.craigslist.org/web/", "http://auburn.craigslist.org/cpg/", "http://auburn.craigslist.org/eng/", "http://auburn.craigslist.org/sof/", "http://auburn.craigslist.org/sad/"]
于 2012-05-15T11:36:52.227 回答
11
a = ["auburn", "http://auburn.craigslist.org/web/", "http://auburn.craigslist.org/cpg/", "http://auburn.craigslist.org/eng/", "http://auburn.craigslist.org/sof/", "http://auburn.craigslist.org/sad/"]

a.drop(1).each { |m| puts m }

#=> http://auburn.craigslist.org/web/
#   http://auburn.craigslist.org/cpg/
#   http://auburn.craigslist.org/eng/
#   http://auburn.craigslist.org/sof/
#   http://auburn.craigslist.org/sad/
于 2012-05-15T11:49:03.243 回答
3

a[1..-1] 将返回删除第一项的数组。

于 2012-05-15T11:37:41.833 回答
2

只是简单地选择你需要的元素怎么样:

a.grep(/^http:/).each { ... }

或者,如果您不希望不必要地创建新的数组副本:

a.each { |e| 
  next if !e.match(/^http:/)
  ...
}
于 2012-05-15T12:21:03.120 回答
1

尝试切片

arr = ["auburn", "http://auburn.craigslist.org/web/", "http://auburn.craigslist.org/cpg/", "http://auburn.craigslist.org/eng/", "http://auburn.craigslist.org/sof/", "http://auburn.craigslist.org/sad/"]
arr.slice(1..-1)

编辑

像这样使用它:

arr.slice(1..-1).each do |p|
  puts p
end
于 2012-05-15T11:46:24.197 回答