我看到有在Ruby中一个相对较新的功能,它允许链式迭代 - 换句话说,而不是each_with_indices { |x,i,j| ... }
你可能会做each.with_indices { |x,i,j| ... }
,其中#each
返回Enumerator
对象,Enumerator#with_indices
导致额外的产量参数被包括在内。在Ruby的C扩展实现链接的迭代器
因此,Enumerator
有其自己的方法#with_index
,大概是一维对象,source found here。但我无法弄清楚将其适用于其他对象的最佳方法。
要清晰,响应评论: Ruby没有一个#each_with_indices
现在 - 这只是有一个#each_with_index
。 (这就是为什么我要创建一个)
一连串的问题,自己的链接:
- 一个怎样适应链式迭代到一个维对象?只需做一个
include Enumerable
? - 推测上述(#1)不适用于n三维对象。会创建一个
EnumerableN
类,从Enumerable
派生,但#with_index
转换为#with_indices
? - 可以使用C编写的Ruby扩展完成#2吗?例如,我有一个矩阵类,它存储各种类型的数据(浮点数,双精度数,整数,有时是常规的Ruby对象,等)。枚举需要首先根据下面的示例检查数据类型(
dtype
)。
例子:
VALUE nm_dense_each(VALUE nm) {
volatile VALUE nm = nmatrix; // Not sure this actually does anything.
DENSE_STORAGE* s = NM_STORAGE_DENSE(nm); // get the storage pointer
RETURN_ENUMERATOR(nm, 0, 0);
if (NM_DTYPE(nm) == nm::RUBYOBJ) { // matrix stores VALUEs
// matrix of Ruby objects -- yield those objects directly
for (size_t i = 0; i < nm_storage_count_max_elements(s); ++i)
rb_yield(reinterpret_cast<VALUE*>(s->elements)[i]);
} else { // matrix stores non-Ruby data (int, float, etc)
// We're going to copy the matrix element into a Ruby VALUE and then operate on it. This way user can't accidentally
// modify it and cause a seg fault.
for (size_t i = 0; i < nm_storage_count_max_elements(s); ++i) {
// rubyobj_from_cval() converts any type of data into a VALUE using macros such as INT2FIX()
VALUE v = rubyobj_from_cval((char*)(s->elements) + i*DTYPE_SIZES[NM_DTYPE(nm)], NM_DTYPE(nm)).rval;
rb_yield(v); // yield to the copy we made
}
}
}
所以,我的三个问题合而为一:我怎么会写,在C,一个#with_indices
到链到上述NMatrix#each
方法?
我并不特别想让任何人觉得我要求他们为我编码,但如果您确实想要,我们很乐意让您参与我们的项目。 =)
但是如果你知道网络上其他地方的一些例子如何完成这个例子,那么这将是完美的 - 或者如果你可以用文字解释,那也是可爱的。
不,没有这样的功能。 Ruby 1.9中没有提及任何内容。 Ruby 2.0中没有提到你提到的这种东西。然而,Ruby有一个不同的东西叫'each_with_index'。 Ruby 1.9引入了'with_index'。 – sawa 2013-05-02 06:29:38
好的,解决了我的问题 - 现在已经是Ruby的一般了。你有没有下降?我可以问为什么?这是一个非常仔细的书面问题。 – 2013-05-02 15:19:29
@sawa:他不问Ruby的功能。这是一个高层次的问题,他是一个开发人员,可能是NMatrix团队的一员,他基本上要求在C中编写Ruby方法的Ruby方式是什么:-)我是(目前)Marc-Andre的Matrix用户,以及我很高兴有NMatrix作为替代方案。 – 2013-05-02 15:34:19