[英]Ruby 'First and Rest' Logic
My app is reaching a point where I must begin optimizing for performance. 我的应用程序正在达到我必须开始优化性能的程度。 I've posted some code from my view that I feel can be improved.
我发布了一些我认为可以改进的代码。
In the view, I am treating the first item in the index a certain way and the rest of the items another way. 在视图中,我以某种方式处理索引中的第一个项目,而另一个方式处理其余项目。 Each time a new item is iterated over, it is being checked (Ruby asks itself.. does this item have an index of 0?)
每次迭代一个新项目时,都会检查它(Ruby问自己..这个项目的索引是0吗?)
I feel like performance can be improved if I can stop that behavior by treating the first item special with index.first?
如果我可以通过使用
index.first?
处理第一个特殊项目来阻止这种行为,我觉得性能可以提高index.first?
and treating the other items another way (without even checking whether they have an index of zero) How can this be done? 并以另一种方式处理其他项目(甚至没有检查它们的索引是否为零)如何做到这一点?
<% @links.each_with_index do |link, index| %>
<% if link.points == 0 then @points = "?" else @points = link.points %>
<% end %>
<% if index == 0 then %>
<h1> First Item </h1>
<% else %>
<h1> Everything else </h1>
<% end %>
<% end %>
<% end %>
You can do this non-destructively like so: 您可以像这样非破坏性地执行此操作:
first, *rest = *my_array
# Do something with 'first'
rest.each{ |item| … }
…where first
will be the first element (or nil
if my_array was empty) and rest
will always be an array (possibly empty). ...
first
是第一个元素(如果my_array为空则为nil
), rest
将始终为数组(可能为空)。
You can get the same results more easily if it's OK to modify your array: 如果可以修改数组,则可以更轻松地获得相同的结果:
# remove the first item from the array and return it
first = my_array.shift
# do something with 'first'
my_array.each{ |item| … }
However, this will only clean up your code; 但是,这只会清理您的代码; it will make no measurable performance difference.
它不会产生可衡量的性能差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.