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

AJF*_*day 6 ruby arrays

我正在使用一系列midi音高,看起来像这样......

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
] 
Run Code Online (Sandbox Code Playgroud)

在这种情况下,音高在索引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
Run Code Online (Sandbox Code Playgroud)

预期输出格式为:

pitch_at_step(pitches, 0) # 60
pitch_at_step(pitches, 2) # 60
pitch_at_step(pitches, 4) # 67
pitch_at_step(pitches, 8) # 67
Run Code Online (Sandbox Code Playgroud)

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

小智 4

如果数组不大,你可以使用这样的东西:

pitches[0..index].compact.last
Run Code Online (Sandbox Code Playgroud)

这看起来更整洁,但对于大数据数组来说,它不如你的那么好