说我有这样的数组:
["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/"]
我想要做的只是处理此数组中的网址 - 这些网址始终位于element[1]
并上线。
我该怎么做?
答案 0 :(得分:11)
这仅显示从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/"]
答案 1 :(得分:9)
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/
答案 2 :(得分:3)
a [1 ..- 1]将返回数组,并删除第一个项目。
答案 3 :(得分:2)
只需选择所需的元素即可:
a.grep(/^http:/).each { ... }
或者,如果您不希望不必要地创建新的阵列副本:
a.each { |e|
next if !e.match(/^http:/)
...
}
答案 4 :(得分: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