Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you select every nth item in an array?

I'm looking to find a way in Ruby to select every nth item in an array. For instance, selecting every second item would transform:

["cat", "dog", "mouse", "tiger"] 

into:

["dog", "tiger"] 

Is there a Ruby method to do so, or is there any other way to do it?

I tried using something like:

[1,2,3,4].select {|x| x % 2 == 0} # results in [2,4] 

but that only works for an array with integers, not strings.

like image 533
sjsc Avatar asked Jan 14 '11 08:01

sjsc


People also ask

How do you find the nth element of an array in Python?

Use list indexing to get the nth element of a list. Use list indexing syntax list[index] with n - 1 as index , where n represents a value's placement in the list, to retrieve the respective nth element of a list.

How do I find the second element of an array?

To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2) . The at method returns the array element at the specified index.


1 Answers

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} 
like image 117
Mladen Jablanović Avatar answered Sep 17 '22 05:09

Mladen Jablanović