Ruby-on-rails 如何选择数组中的每第 n 个项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4689186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:05:34  来源:igfitidea点击:

How do you select every nth item in an array?

ruby-on-railsruby

提问by sjsc

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:

我希望在 Ruby 中找到一种方法来选择数组中的每个第 n 项。例如,选择每隔一个项目将转换:

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

into:

进入:

["dog", "tiger"]

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

有没有 Ruby 方法可以做到这一点,或者有没有其他方法可以做到这一点?

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.

但这仅适用于带有整数的数组,而不适用于字符串。

采纳答案by mu is too short

You could also use step:

您还可以使用步骤:

n = 2
a = ["cat", "dog", "mouse", "tiger"]
b = (n - 1).step(a.size - 1, n).map { |i| a[i] }

回答by Mladen Jablanovi?

You can use Enumerable#each_slice:

您可以使用Enumerable#each_slice

["cat", "dog", "mouse", "tiger"].each_slice(2).map(&:last)
# => ["dog", "tiger"]

Update:

更新:

As mentioned in the comment, lastis not always suitable, so it could be replaced by first, and skipping first element:

正如评论中提到的,last并不总是合适的,所以它可以替换为first, 并跳过第一个元素:

["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:

IMO,最优雅的是使用.select.with_index,Nakilon 在他的评论中建议:

["cat", "dog", "mouse", "tiger"].select.with_index{|_,i| (i+1) % 2 == 0}

回答by anshul

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"]

回答by Antonija ?imi?

You can simply use values_atmethod. You can find it easily in documentation.

您可以简单地使用values_at方法。您可以在文档中轻松找到它。

Here are some examples:

这里有些例子:

array = ["Hello", 2, "apple", 3]
array.values_at(0,1) # pass any number of arguments you like
=> ["Hello", 2]

array.values_at(0..3) # an argument can be a range
=>["Hello", 2, "apple", 3]

I believe this would fix your problem with "dog" and "tiger"

我相信这会解决你的“狗”和“老虎”问题

array = ["cat", "dog", "mouse", "tiger"]
array.values_at(1,3)

and with your another array

和你的另一个阵列

[1,2,3,4].values_at(1,3)
=> [2, 4] 

回答by coorasse

If what you are looking for, is to select only odd or even numbers, there's a very simple way:

如果您要寻找的是仅选择奇数或偶数,则有一种非常简单的方法:

animals.select.with_index{ |_, i| i.odd? }

e.g.

例如

['a','b','c','d'].select.with_index{ |_,i| i.odd? }
# => ["b", "d"]

回答by Zabba

If you need that in other places, you could add a method to Enumerable:

如果您在其他地方需要它,您可以添加一个方法Enumerable

module Enumerable
   def select_with_index
      index = -1
      (block_given? && self.class == Range || self.class == Array)  ?  select { |x| index += 1; yield(x, index) }  :  self
   end
end

p ["cat", "dog", "mouse", "tiger"].select_with_index { |x, i| x if i % 2 != 0 }

Note: This is not my original code. I got it from herewhen I had had the same need as you.

注意:这不是我的原始代码。当我和你有同样的需求时,我从这里得到了它。

回答by tokland

Yet another ways:

还有一种方式:

xs.each_with_index.map { |x, idx| x if idx % 2 != 0 }.compact

xs.each_with_index.select { |x, idx| idx % 2 }.map(&:first)

xs.values_at(*(1...xs.length).step(2))

回答by Darren Hicks

I like both Anshul's and Mu's answers and want to refine and simplify them a bit by submitting each as a monkeypatch to Enumerable:

我喜欢 Anshul 和 Mu 的答案,并希望通过将每个答案作为 Monkeypatch 提交给 Enumerable 来改进和简化它们:

Mu's

穆氏

module Enumerable
  def every_nth(n)
    (n - 1).step(self.size - 1, n).map { |i| self[i] }
  end
end 

Anshul's

安舒尔

module Enumerable
  def every_nth(n)
    (0... self.length).select{ |x| x%n == n-1 }.map { |y| self[y] }
  end
end 

Then it is very easy to work with. For example, consider:

然后它很容易使用。例如,考虑:

a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]

a.every_nth(2)
 => [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24] 

a.every_nth(3)
 => [3, 6, 9, 12, 15, 18, 21, 24]

a.every_nth(5)
 => [5, 10, 15, 20, 25]

回答by dawn

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

my_array = [“猫”、“狗”、“老鼠”、“老虎”]

my_new_array = my_array.select {|x| index(x) % 2 == 0}

my_new_array = my_array.select {|x| 索引(x)% 2 == 0}

回答by JCLL

class Array
  def every(n)
    select {|x| index(x) % n == 0}
  end
end