我正在使用一系列midi音高,看起来像这样……
- pitches = [
- 60,nil,67,nil
- ]
在这种情况下,音高在索引1,2和3上仍为60.
在指数4之后,投球仍然是67.
如何编写方法来识别先前的非零值?
我目前认为这样做的唯一方法看起来有点笨拙:
- 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
预期输出格式为:
- pitch_at_step(pitches,0) # 60
- pitch_at_step(pitches,2) # 60
- pitch_at_step(pitches,4) # 67
- pitch_at_step(pitches,8) # 67
这是最好的解决方案吗?是否有更整洁和/或更有效的方式?
解决方法
如果数组不大,你可以使用这样的东西:
- pitches[0..index].compact.last
这看起来更整洁,但它不如大数据阵列那么好