I'm working with an array of midi pitches, which looks like this...
pitches = [
60, nil, nil, nil, 67, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil
]
In this case, the pitch is still 60 on indexes 1, 2 and 3.
Following index 4, the pitch is still 67.
How can I write a method to identify the previous non-nil value?
The only way I can currently think to do it looks a little clumsy:
def pitch_at_step(pitches,step)
if pitches.any?
x = pitches[step]
until x != nil
index -= 1
x = pitches[step]
end
x
else
nil
end
end
The expected output is in the format:
pitch_at_step(pitches, 0) # 60
pitch_at_step(pitches, 2) # 60
pitch_at_step(pitches, 4) # 67
pitch_at_step(pitches, 8) # 67
Is this the best solution? is there a tidier and/or more efficient way?