Keren
Keren

Reputation: 217

Ternary operator syntax issue

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.

Upvotes: 1

Views: 554

Answers (2)

Mike S
Mike S

Reputation: 11429

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

Upvotes: 2

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84453

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.

Upvotes: 2

Related Questions