Ruby Ruby Basics Conditionals A Better "check_speed" Method

Chris Drummond
Chris Drummond
943 Points

This version of the check_speed only prints "speed OK" if the speed is exactly 55 miles per hour. It would be better to

Original code:

def check_speed(speed) if speed < 45 puts "too slow" elsif speed >= 45 && <= 60 puts "speed ok" else speed > 60 puts "too fast" end end

error:Bummer: There seems to be an error in your code: 4: syntax error, unexpected <= (SyntaxError)

Got past this by updating the code the the below code but get an error for the else statement:

def check_speed(speed) if speed < 45 puts "too slow" elsif speed >= 45 puts "speed ok" else speed > 60 puts "too fast" end end

error: Bummer: We called check_speed with an argument greater than 60, but it didn't print "too fast".

Any suggestions?

program.rb
def check_speed(speed)
  if speed < 45
    puts "too slow"
  elsif speed >= 45 
    puts "speed OK"
  else speed > 60
    puts "too fast"
  end
end

1 Answer

Using your code and a speed value of 61 would print "speed OK" because 61 is >= 45 so the conditional will never get to the else statement. You only want to print "speed OK" if the speed is greater than or equal to 45 and if it is less that or equal to 60 (speed values of 45-60). Also, else statements don't need conditions, so you can remove the speed > 60 from the else statement.

def check_speed(speed)
  if speed < 45
    puts "too slow"
  elsif speed >= 45 && speed <= 60
    puts "speed OK"
  else
    puts "too fast"
  end
end