简体   繁体   中英

Undefined method using ternary operators in Ruby

trying to write two methods in the same file to check number arguments. The first method passes all tests fine but the second keeps giving me the NoMethodError even though the method by its self passes.

heres my code:

def unsafe?(speed)
        if speed < 40 
            return true
        elsif speed > 60
            return true 
        else
            return false
end

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

You're missing an end keyword to if . This is what it looks like if you indent the code properly:

def unsafe?(speed)
  if speed < 40 
    return true
  elsif speed > 60
    return true 
  else
    return false
  end
  
  def not_safe?(speed)
    speed < 40 || speed > 60 ? true : false
  end
end

As you can see the code will never get to def not_safe?(speed) as the method has already returned. Ruby allows nested method definitions yet their actual use is universally discouraged .

This is what it should look like:

def unsafe?(speed)
  if speed < 40 
    return true
  elsif speed > 60
    return true 
  else
    return false
  end
end

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

But this is really is a very overcomplicated way of doing something that can be handled with:

def unsafe?(speed)
  !speed.between(40,60)
end

The whole idea of using the ternary operator is just plain strange as speed < 40 || speed > 60 speed < 40 || speed > 60 evaluates to true or false anyways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM