Ruby数组 – 如何使值保持在nil值之上

前端之家收集整理的这篇文章主要介绍了Ruby数组 – 如何使值保持在nil值之上前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用一系列midi音高,看起来像这样……
  1. pitches = [
  2. 60,nil,67,nil
  3. ]

在这种情况下,音高在索引1,2和3上仍为60.

在指数4之后,投球仍然是67.

如何编写方法来识别先前的非零值?

我目前认为这样做的唯一方法看起来有点笨拙:

  1. def pitch_at_step(pitches,step)
  2. if pitches.any?
  3. x = pitches[step]
  4. until x != nil
  5. index -= 1
  6. x = pitches[step]
  7. end
  8. x
  9. else
  10. nil
  11. end
  12. end

预期输出格式为:

  1. pitch_at_step(pitches,0) # 60
  2. pitch_at_step(pitches,2) # 60
  3. pitch_at_step(pitches,4) # 67
  4. pitch_at_step(pitches,8) # 67

这是最好的解决方案吗?是否有更整洁和/或更有效的方式?

解决方法

如果数组不大,你可以使用这样的东西:
  1. pitches[0..index].compact.last

这看起来更整洁,但它不如大数据阵列那么好

猜你在找的Ruby相关文章