如何在Array#delete_if中引用元素的索引 [英] How to refer the index of an element in Array#delete_if
本文介绍了如何在Array#delete_if中引用元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想构建一个自定义方法Array#drop_every(n)
(我知道这是猴子补丁,我正在做家庭作业),该方法将返回一个新数组,省略每个第n个元素:
I want to build a custom method Array#drop_every(n)
(I know it's monkey patching, I am doing this for a homework), which returns a new array omitting every nth element:
[4, 8, 15, 16, 23, 42].drop_every(2) # [4, 15, 23]
我想用Array#delete_if
实现它,但是通过引用索引而不是元素本身(类似于each_index
)是这样的:
I want to implement it with Array#delete_if
, but by referring to the index and not to the element itself, (similar to each_index
) something like this:
def drop_every(step)
self.delete_if { |index| index % step == 0 }
end
我该怎么做?我不坚持使用delete_if
,我也查看了drop_while
和reject
,欢迎其他建议.
How do I do this? I don't insist on using delete_if
, I also looked at drop_while
and reject
, other suggestions are welcome.
推荐答案
def drop_every(step)
reject.with_index { |x,i| (i+1) % step == 0 }
end
[4, 8, 15, 16, 23, 42].reject.with_index{|x,i| (i+1) % 2 == 0}
# => [4, 15, 23]
[4, 8, 15, 16, 23, 42].reject.with_index{|x,i| (i+1) % 3 == 0}
# => [4, 8, 16, 23]
这篇关于如何在Array#delete_if中引用元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文