我怎么能实现这个?我认为我的解决方案很脏,我想做得更好。我认为在 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
******* 编辑 *******
对于那些想知道的人,这就是我最终所做的:
在 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
在 Rails 加载后,Rails 会立即自动加载这些文件。我还使用了向方法提供参数的 railsy 方式,因为我认为这有助于提高代码的可读性,而且我是一个很好的可读代码迷 :) 我扩展了核心类“Array”,现在我可以对项目中的每个数组执行以下操作:
>> 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]
我现在将使用它在视图的不同列中显示来自数据库的条目。我喜欢它的地方是我不必调用任何紧凑的方法或东西,因为当您将 nil 对象传递给视图时,rails 会抱怨。现在它可以正常工作了。我也想过让 JS 为我做这一切,但我更喜欢这种方式,使用 960 Grid 系统 ( http://960.gs )