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 Operators and Control Structures Logical Operators The And (&&) Operator

Bruce Lagerquist
Bruce Lagerquist
603 Points

I'm not clear on why this piece of code is not passing. Can you give me a hint?

My code is working in the workspace, I might not be reading the question correctly.

Thanks

ruby.rb
def check_speed(car_speed)
  if (car_speed >= 40) && (car_speed <= 50)
    puts "safe"
  else
    puts "unsafe"
  end
end  
check_speed 45

1 Answer

andren
andren
28,526 Points

The problem is that the challenge instructs you to return "safe" or "unsafe". Your solution doesn't actually return those strings, you print them using puts.

Returning a value and printing it are quite different, for simple tasks they might appear to act the same (especially in the Ruby REPL) but their differences will become apparent later on.

For now just know that they do very different things and when a task asks you to return a value you do have to actually return it, not just print it. Returning a value is done using the return keyword, like this:

def check_speed(car_speed)
  if (car_speed >= 40) && (car_speed <= 50)
    return "safe"
  else
    return "unsafe"
  end
end  

Ruby also has a feature called "Implicit return" where it will automatically return the last value that is handled by your function. So in the case where the value is at the end of the function, or you are using an if/else statement like you are then you can technically skip using the return keyword like this:

def check_speed(car_speed)
  if (car_speed >= 40) && (car_speed <= 50)
    "safe"
  else
    "unsafe"
  end
end  

The above code is valid, but arguably harder to read. I would generally recommend explicitly using the return keyword like I do in the first example since that is a bit clearer, and will also prepare you for other languages since most languages do not have implicit returns like Ruby does.

Bruce Lagerquist
Bruce Lagerquist
603 Points

Thank you. I just figure that out. All good now.

Mike Hickman
Mike Hickman
19,817 Points

Perfect response @andren - I'd +10 this if I could.