Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Operators and Control Structures Logical Operators The And (&&) Operator

Ben M
Ben M
2,143 Points

having trouble with this question ,any ideas ?!

The method below checks the speed of a car and returns a string value: either "safe" or "unsafe". Return "safe" if: The car_speed passed in as an argument is greater than or equal to the number 40. The car_speed passed in as an argument is less than or equal to the number 50. Otherwise, return "unsafe". Hint: You should use the && logical operator to accomplish this task. :)

ruby.rb
def check_speed(car_speed)
  # write your code here
  print "what is your speed?"
  car_speed = gets.chomp.to_i
  if ( car_speed >= 40 ) && ( car_speed <= 50 )
    puts "safe"  
  end
  else
    puts "unsafe"
  end

6 Answers

Ellis Briggs
Ellis Briggs
11,108 Points

Use another if statement instead of an else, if you are using else, it counts as the end of the first if.

def check_speed(car_speed) print "what is your speed?" car_speed = gets.chomp.to_i if ( car_speed >= 40 ) && ( car_speed <= 50 ) puts "safe" if ( car_speed <= 50 ) && ( car_speed >= 40 ) puts "unsafe" end

Ellis Briggs
Ellis Briggs
11,108 Points

Sorry I have no idea what I was thinking, try putting return instead of puts.

Ellis Briggs
Ellis Briggs
11,108 Points

Oh just seen that you put an end after the first 'if' should probably look like : def check_speed(car_speed) # write your code here print "what is your speed?" car_speed = gets.chomp.to_i if ( car_speed >= 40 ) && ( car_speed <= 50 ) return "safe" else return "unsafe" end

martinaraignee
martinaraignee
12,786 Points

def check_speed(car_speed) print "what is your speed?" car_speed = gets.chomp.to_i if (car_speed >= 40) && (car_speed <= 50) puts "safe" elsif (car_speed < 40) && (car_speed > 50) puts "unsafe" end end

for some reasons doesn't work. Could you help, please

Ellis Briggs
Ellis Briggs
11,108 Points

Use return instead of puts as you are returning the final value to the function rather then displaying it.