如何将多行形式的条件转换为后缀形式?

How do I turn the multiple-line form of conditions to postfix form?

这是一个多行形式的条件语句:

if button_down?(@buttons[:forward]) and @speed < @max_speed
  @speed += @acceleration 
elsif button_down?(@buttons[:backward]) and @speed > -@max_speed
  @speed -= @acceleration
end

我想把它转换成后缀形式:

@speed += @acceleration if button_down?(@buttons[:forward]) and @speed < @max_speed
@speed -= @acceleration elsif button_down?(@button[:backward]) and @speed > -@max_speed

上面的代码引发了:

syntax error, unexpected keyword_elsif, expecting end-of-input

如何以正确的方式做到这一点?总是选择 if

我怀疑我理解你所说的“高效”是什么,但在这种特殊情况下我会选择:

@speed +=
  case
  when button_down?(...) then @acceleration 
  when button_down?(...) then -@acceleration
  else 0
  end

甚至:

@speed += @acceleration *
  case
  when button_down?(...) then 1
  when button_down?(...) then -1
  else 0
  end

我建议结合使用 case 语句和辅助方法来 DRY 代码。

@speed +=
case
when satisfy?(:forward, @speed)   then @acceleration
when satisfy?(:backward, -@speed) then -@acceleration
else 0
end

def satisfy?(direction, speed)
  button_down?(direction) && speed < @max_speed
end

我可能会将一些逻辑提取到单独的方法中:

def increase_speed
  @speed = [@max_speed, @speed + @acceleration].min
end

def decrease_speed
  @speed = [-@max_speed, @speed - @acceleration].max
end

使用这些方法,您可以编写如下内容:

increase_speed if button_down?(@buttons[:forward])
decrease_speed if button_down?(@buttons[:backward])