Prob with each_with_index

lo there all,

i am having a problem making each_with_index do what i need it to do.
the issue is…

i need to evaluate the gpm of a flow sensor.
we are skipping over three database entries to get the values.
difference in value / difference in time = gpm. ok, easy enough.

but this code

@flow_sensor.flow_hits.each_with_index do |hit, i|
if i > 4 # start with 3rd hit in db
time_diff = hit[i].date_time.to_i -
hit[i-3].date_time.to_i
value_diff = hit[i].value - hit[i-3].value
min = time_diff / 60
val = value_diff / min
plots.push(val)
times.push(hit[i].date_time)
end
end

is giving me a nil value evaluating nil.date_time

this is for a rails app by the way.

i know i have the models set up right, because other functions are
working.
thats why i think my structure is wrong.

thanks.

shawn bright wrote:

@flow_sensor.flow_hits.each_with_index do |hit, i|
if i > 4 # start with 3rd hit in db
No, you’re starting with the 5th !!

Index are zero-based, to you need i >= 2 to get the third one.

Vince

On 12/21/06, Chunyun Z. [email protected] wrote:

         min = time_diff / 60
      if i > 4 # start with 3rd hit in db

is giving me a nil value evaluating nil.date_time

cool beans, thanks gents.
sk

hit passed in the block is the elment, not the array.

Try this:

@flow_sensor.flow_hits.each_with_index do |hit, i|
if i > 4 # start with 3rd hit in db
time_diff = hit.date_time.to_i -
@flow_sensor.flow_hits[i-3].date_time.to_i
value_diff = hit.value - @flow_sensor.flow_hits[i-3].value
min = time_diff / 60
val = value_diff / min
plots.push(val)
times.push(hit.date_time)
end
end