如何选择数组中的每第 n 个项目?
问题描述:
我希望在 Ruby 中找到一种方法来选择数组中的每个第 n 项.例如,选择每第二个项目将转换:
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"]
进入:
["dog", "tiger"]
是否有 Ruby 方法可以做到这一点,或者还有其他方法可以做到这一点?
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.
答
您也可以使用 step:
You could also use step:
n = 2
a = ["cat", "dog", "mouse", "tiger"]
b = (n - 1).step(a.size - 1, n).map { |i| a[i] }