How do you select every nth item in an array?

You can use Enumerable#each_slice:

["cat", "dog", "mouse", "tiger"].each_slice(2).map(&:last)
# => ["dog", "tiger"]

Update:

As mentioned in the comment, last is not always suitable, so it could be replaced by first, and skipping first element:

["cat", "dog", "mouse", "tiger"].drop(1).each_slice(2).map(&:first)

Unfortunately, making it less elegant.

IMO, the most elegant is to use .select.with_index, which Nakilon suggested in his comment:

["cat", "dog", "mouse", "tiger"].select.with_index{|_,i| (i+1) % 2 == 0}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)