Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Ruby Basics Conditionals A Better "check_speed" Method

Chris Drummond
Chris Drummond
1,469 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