gpt4 book ai didi

ruby 'First and Rest' 逻辑

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:23 27 4
gpt4 key购买 nike

我的应用已经到了我必须开始优化性能的地步。我已经发布了一些我认为可以改进的代码。

在 View 中,我以某种方式处理索引中的第一个项目,并以另一种方式处理其余项目。每次迭代一个新项目时,都会对其进行检查(Ruby 会问自己……这个项目的索引是否为 0?)

我觉得如果我可以通过用 index.first? 特殊处理第一个项目并以另一种方式处理其他项目(甚至不检查它们是否有索引)来停止这种行为,我觉得性能可以提高为零)如何做到这一点?

  <% @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 %>

最佳答案

您可以像这样非破坏性地执行此操作:

first, *rest = *my_array
# Do something with 'first'
rest.each{ |item| … }

…其中 first 将是第一个元素(或者 nil 如果 my_array 为空)并且 rest 将始终是一个数组(可能为空).

如果可以修改数组,您可以更轻松地获得相同的结果:

# remove the first item from the array and return it
first = my_array.shift
# do something with 'first'
my_array.each{ |item| … }

但是,这只会清理您的代码;它不会产生可衡量的性能差异。

关于 ruby 'First and Rest' 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10373963/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com