Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

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
question from:https://stackoverflow.com/questions/65836576/undefined-method-using-ternary-operators-in-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 evaluates to true or false anyways.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...