How to start looping in an array from the second element using each? - ruby

Say I have an array like this:

["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/"] 

What I would like to do is work only with the URLs in this array, which will always start with element[1] and go up.

How to do it?

+4
source share
5 answers

This only shows items starting at 1 (second item), -1 indicates the last item

 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/"] pa[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/"] 
+9
source
 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/ 
+8
source

How to simply select the items you need:

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

Or if you do not want new copies of arrays to be created unnecessarily:

 a.each { |e| next if !e.match(/^http:/) ... } 
+2
source

a [1 ..- 1] will return an array with the first element removed.

+1
source

try the snippet :

 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) 

edit :

use it like:

 arr.slice(1..-1).each do |p| puts p end 
+1
source

Source: https://habr.com/ru/post/1412561/


All Articles