Chr*_*ier 2 ruby arrays refactoring
我有一个看起来像这样的循环
def slow_loop(array)
array.each_with_index do |item, i|
next_item = array[i+1]
if next_item && item.attribute == next_item.attribute
do_something_with(next_item)
end
end
end
Run Code Online (Sandbox Code Playgroud)
除了改变do_something_with被调用的方式,我怎样才能使这个表现更好?
谢谢,
-C
PS
由于看起来这是一个'O(n)'操作,显然没有在这里获得性能,所以我选择的答案是使用已经封装了这个操作的ruby方法.感谢大家的帮助
正如其他人所说,你不会提高性能,但你可以这样干净利落地做到这一点:
array.each_cons(2) do |a, b|
do_something_with(b) if a == b
end
Run Code Online (Sandbox Code Playgroud)