简体   繁体   English

Ruby 脚本忽略条件和中断方法而不会抛出错误

[英]Ruby script ignores conditional and breaks method without throwing errors

I have this (I believe) straight and easy method meant to verify if a certain string only includes numbers and isn't empty.我有这个(我相信)直接和简单的方法来验证某个字符串是否只包含数字而不是空的。

class String

    def is_number?
    
        puts "Here it's working, 1"
    
        if self.scan(/\D/).empty? and self != ""
            return true
            puts "true"
        else
            return false
            puts "false"
        end
        
        puts "Here it's working, 2"
    end
    
end

"asd".is_number?
puts "Here it's working, 3"

The result is quite astonishing to me:结果令我非常惊讶:

结果

The method works until before the conditional.该方法在条件之前有效。 At that point it doesn't go with the "then" nor the "else" options (which, up to today, I never thought to be an option too), and instead breaks the method.在这一点上,它不适合“then”或“else”选项(直到今天,我从未想过也是一个选项),而是打破了方法。 Then, it proceeds to the following command.然后,它继续执行以下命令。 Finally, at the end of the program it sits there without throwing any error.最后,在程序结束时,它坐在那里而不会抛出任何错误。

I honestly don't know how to proceed at this point.老实说,我现在不知道如何进行。

When you used return in a method it will not execute any code after that, if you are expecting true / false to print you should put it above the return statement当你在一个方法中使用return ,它之后不会执行任何代码,如果你希望打印true / false ,你应该把它放在return语句之上

def is_number?
  puts "Here it's working, 1"
  if self.scan(/\D/).empty? and self != ""
    puts "true"
    return true
  else
    puts "false"
    return false
  end   
  puts "Here it's working, 2"
end

Note:- "Here it's working, 2" statement will never execute as there will be return statement before that.注意:- "Here it's working, 2"语句将永远不会执行,因为在此之前会有return语句。

it doesn't go with the "then" nor the "else" options它不适合“then”或“else”选项

No, this is not what happens here, as described in the answer from Salil.不,这不是这里发生的情况,如 Salil 的回答中所述。

For the future, if you formulate a hypothesis about your code, you should prove or disprove it.对于未来,如果你对你的代码提出一个假设,你应该证明或反驳它。 Not for us, for yourself.不是为了我们,是为了你自己。 Else how do you know this is actually what is happening?否则你怎么知道这实际上是发生了什么?

For example, something like this would reliably verify that the control does indeed enter one of the conditional branches.例如,这样的事情可以可靠地验证控件确实进入了条件分支之一。

if self.scan(/\D/).empty? and self != ""
  #return true
  #puts "true"
  raise "error from if branch"
else
  #return false
  #puts "false"
  raise "error from else branch"
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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