用下一个索引项目减去当前项目

时间:2018-08-28 23:06:21

标签: ruby-on-rails ruby ruby-on-rails-5

我试图用下一个索引项减去循环中的当前项,但我刚得到以下错误:未定义的方法[[]”表示0.0:Float

<% @trial.methods.each_with_index do |e, index| %>
  <%= (e.total - e.total[index+1]) %><br />
  <%= Time.at(e.try(:assessment).try(:assessment_date)/1000).strftime("%d/%m/%Y") %><br />
  <%= e.try(:assessment).try(:degrees) %>
<% end %>

3 个答案:

答案 0 :(得分:4)

我认为有一种更简便的方法。看下面的例子。

# An array of 5 random numbers
a =  [7,12,1,2,3]

# Iterate through the indices of the array
a.each_index do |i|
    # We only show the result of a[i+1] - a[i]
    # given i+1 is still in range of the array
    puts "#{a[i+1] - a[i]}" if (i+1) < a.length
end

这应在新行中分别输出5 -11 1 1

类似地,您可以执行以下操作:

<% @trial.methods.each_index do |i| %>
  <% if i + 1 < e.total.length %>
    <%= (e.total[i] - e.total[index+1]) %>
  <% else %>
    <%= 0 %>
  <% end %>
<% end %>

答案 1 :(得分:2)

使用#each_cons构建连续对的子数组,然后将其映射:

array = [7,12,1,2,3]

array.each_cons(2).map{ |e| e.last - e.first }

# => [5, -11, 1, 1]

一个备选方案:

array.each_cons(2).map{ |a, b| b - a }

当然,您可以更改为a - b或任何您需要的内容。

第一部分是这样的:

array.each_cons(2).each {|e| p e}

# => [7, 12]
# => [12, 1]
# => [1, 2]
# => [2, 3]

答案 2 :(得分:0)

您可以使用Enumerable#reduce实现此目的:

a =  [7,12,1,2,3]
a.reduce(&:-) # -11

所以对于您的情况:

@trial.methods.map{|e| e.total}.reduce(&:-)

请参见https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-reduce的用法