Ruby/Rails:从数组中获取索引可被x整除的元素

Pat*_*ity 3 ruby arrays ruby-on-rails modulo

我怎么能实现这个?我认为我的解决方案很脏,我想做得更好.我认为在Ruby中有一种简单的方法可以做到这一点,但我不记得了.我想在Rails中使用它,所以如果Rails提供类似的东西也可以.用法应该是这样的:

fruits = ['banana', 'strawberry', 'kiwi', 'orange', 'grapefruit', 'lemon', 'melon']

# odd_fruits should contain all elements with odd indices (index % 2 == 0)
odd_fruits = array_mod(fruits, :mod => 2, :offset => 0)

# even_fruits should contain all elements with even indices (index % 2 == 1)
even_fruits = array_mod(fruits, :mod => 2, :offset => 1)

puts odd_fruits
  banana
  kiwi
  grapefruit
  melon

puts even_fruits
  strawberry
  orange
  lemon
Run Code Online (Sandbox Code Playgroud)

*******编辑*******

对于那些想知道的人,这就是我最终做到的:

在rails项目中,我创建了一个新文件config/initializers/columnize.rb,如下所示:

class Array
  def columnize args = { :columns => 1, :offset => 0 }
    column = []
    self.each_index do |i|
      column << self[i] if i % args[:columns] == args[:offset]
    end
    column
  end
end
Run Code Online (Sandbox Code Playgroud)

Rails加载后,Rails会立即自动加载这些文件.我还使用了为方法提供参数的railsy方法,因为我认为这是为了更好的可读代码的目的,而且我是一个良好的可读代码 - 恋物癖:)我扩展了核心类"数组",现在我可以对项目中的每个数组执行以下操作:

>> arr = [1,2,3,4,5,6,7,8]
=> [1, 2, 3, 4, 5, 6, 7, 8]

>> arr.columnize :columns => 2, :offset => 0
=> [1, 3, 5, 7]
>> arr.columnize :columns => 2, :offset => 1
=> [2, 4, 6, 8]

>> arr.columnize :columns => 3, :offset => 0
=> [1, 4, 7]
>> arr.columnize :columns => 3, :offset => 1
=> [2, 5, 8]
>> arr.columnize :columns => 3, :offset => 2
=> [3, 6]
Run Code Online (Sandbox Code Playgroud)

我现在将使用它在我的视图中的不同列中显示数据库中的条目.我喜欢它的是,我不必调用任何紧凑的方法或东西,因为当你将一个nil对象传递给视图时rails会抱怨.现在它只是有效.我也想过让JS为我做这一切,但我更喜欢这样,使用960网格系统(http://960.gs)

Osc*_*Ryz 5

fruits = ["a","b","c","d"]
even = []
x = 2 
fruits.each_index{|index|
    even << fruits[index] if index % x == 0
}
odds = fruits - even
p fruits
p even
p odds



["a", "b", "c", "d"]
["a", "c"]
["b", "d"]
Run Code Online (Sandbox Code Playgroud)