Search code examples
rubypostfix-notation

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


This is a multiple-line form of conditional statement:

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

I want to convert it into a postfix form this:

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

The code above raises:

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

How can this be made in a correct way? Going with if always?


Solution

  • I doubt I understand what are you calling “efficient,” but in this particular case I would go with:

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

    or even:

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