如何选择数组中的每第 n 个项目? [英] How do you select every nth item in an array?

查看:47
本文介绍了如何选择数组中的每第 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] }

这篇关于如何选择数组中的每第 n 个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆