I'm using ruby 1.8.5, and the each_slice()
method for an array is not working.
我使用的是ruby 1.8.5,数组的each_slice()方法不起作用。
My code is something like:
我的代码是这样的:
array.each_slice(3) do |name,age,sex| ..... end
Is there any other way to implement the same functionality in my older version of ruby.
在我的旧版本的ruby中还有其他实现相同功能的方法吗?
4 个解决方案
#1
5
Bake your own:
烤自己的:
module Enumerable
def each_slice( n )
res = []
self.each do |el|
res << el
if res.size == n then
yield res.dup
res.clear
end
end
yield res.dup unless res.empty?
end
end
#2
1
This guy
这家伙
http://tekhne.wordpress.com/2008/02/01/whence-arrayeach_slice/
http://tekhne.wordpress.com/2008/02/01/whence-arrayeach_slice/
figured out you can
找出你可以
require 'enumerator'
and it works
和它的工作原理
#3
0
I haven't got 1.8.5, but you can try this
我没有1.8.5,但你可以试试这个
0.step(array.size, 3) do |i|
name, age, sex = array[i], array[i+1], array[i+2]
...
end
#1
5
Bake your own:
烤自己的:
module Enumerable
def each_slice( n )
res = []
self.each do |el|
res << el
if res.size == n then
yield res.dup
res.clear
end
end
yield res.dup unless res.empty?
end
end
#2
1
This guy
这家伙
http://tekhne.wordpress.com/2008/02/01/whence-arrayeach_slice/
http://tekhne.wordpress.com/2008/02/01/whence-arrayeach_slice/
figured out you can
找出你可以
require 'enumerator'
and it works
和它的工作原理
#3
0
I haven't got 1.8.5, but you can try this
我没有1.8.5,但你可以试试这个
0.step(array.size, 3) do |i|
name, age, sex = array[i], array[i+1], array[i+2]
...
end