简体   繁体   中英

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?)

I feel like performance can be improved if I can stop that behavior by treating the first item special with 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM