1

I am trying to return "true" if the speed is under 40 or over 60, and false otherwise.

Here's my code:

def not_safe?(speed)

  if speed < 40 || speed > 60 ? true : false

  end
end

and here's the error:

Failure/Error: expect(answer).to eq(false)

expected: false
got: nil

(compared using ==)

I tried putting each argument within parenthesis, as well as using "true" and "false" as strings.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Keren
  • 217
  • 1
  • 6
  • 20

2 Answers2

2

You don't need the if. It should look like this:

def not_safe?(speed)
  speed < 40 || speed > 60 ? true : false
end

irb(main):027:0> not_safe? 30
  => true
irb(main):028:0> not_safe? 50
  => false

As engineersmnky pointed out, there is no need to use the ternary operator here since the expression evaluates to a boolean. So all you need is this:

def not_safe?(speed)
  speed < 40 || speed > 60
end
Mike S
  • 11,329
  • 6
  • 41
  • 76
  • 6
    or just `speed < 40 || speed > 60` since this will always be a boolean response. ternary operator does not really apply here – engineersmnky Nov 06 '15 at 22:02
2

Just Return the Boolean Result of an Expression

Since Ruby methods will return the result of the last expression evaluated, in this case you can simply rely on the Boolean result of your expressions as a return value. The idiomatic way to rewrite your method would be:

def unsafe? speed
  speed < 40 || speed > 60
end

This does what you'd expect:

unsafe? 10
#=> true

unsafe? 50
#=> false 

unsafe? 70
#=> true

This is both easier to read and more idiomatic, and reduces unnecessary clutter in the code. Furthermore, renaming the variable to unsafe? makes it more natural-sounding, and reduces potential confusion over double-negatives when expressing ideas like not_safe? 50 #=> false.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199