How do you select every nth item in an array?
You could also use step:
n = 2
a = ["cat", "dog", "mouse", "tiger"]
b = (n - 1).step(a.size - 1, n).map { |i| a[i] }
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}
How about this -
arr = ["cat", "dog", "mouse", "tiger"]
n = 2
(0... arr.length).select{ |x| x%n == n-1 }.map { |y| arr[y] }
#=> ["dog", "tiger"]