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.
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.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With