Ruby Ruby Basics Conditionals "if" Statements

Christian Szadyr
Christian Szadyr
3,306 Points

Need help with a Ruby Basics objective (newb)

Define a method named check_speed that takes a single number representing a car's speed as a parameter. If the speed is over 55, check_speed should print the message "too fast". If the speed is under 55, check_speed should print the message "too slow". And if the speed is exactly 55, check_speed should print the message "speed OK".

When I run this code in the workspace, it works just like the question asks, however, when I paste the code into the objective, it gives me this error. Can anyone help me figure out what I'm doing wrong? Sorry for my ignorance, i'm new at this... :)

welcome to the speedometer! What speed are you going? too slow Run options: --seed 22599 # Running: E Finished in 0.001504s, 664.7235 runs/s, 0.0000 assertions/s. 1) Error: TestSpeed#test_check_speed: TypeError: String can't be coerced into Fixnum /workdir/program.rb:2:in +' /workdir/program.rb:2:incheck_speed' task_1.txt:15:in `block (2 levels) in test_check_speed' 1 runs, 0 assertions, 0 failures, 1 errors, 0 skips

def check_speed(input)
  print input + " "

puts "welcome to the speedometer!"
answer = check_speed("What speed are you going?")
number = answer.to_i
if number > 55 then puts "too fast"
if number < 55 then puts "too slow"
 if number == 55 then puts "ok"

1 Answer

Steve Hunter
Steve Hunter
Treehouse Moderator 57,564 Points

Hi Christian,

The if conditionals need to be inside the method. Calling the check_speed method doesn't give the output that the challenge is expecting, so the code fails the tests.

There's no need to take user input or prompt for it - the method receives a value which is the speed, it doesn't matter where that comes from. Inside the method, you test this speed for the three conditions. Actually, you test for two conditions; the last is mutually exclusive.

Use an if statement to check if the speed is less than 55, print "Too slow" in that part of the statement; then use elsif to test again whether the speed is greater than 55, outputting "Too fast". Then use an else to print "Speed OK" as there's no other possibility. If speed is neither greater nor less than 55, it must be equal to it.

That all comes out like:

def check_speed(speed)
  if speed < 55
    print "Too slow"
  elsif speed > 55
    print "Too fast"
  else # no condition - no other possible outcomes
    print "speed OK"

You could write three individual if statements but that's inelegant. Combining the conditions in this way is more compact.

I hope that helps and that it makes sense,