简体   繁体   English

Ruby String.index(“ /”)返回-1

[英]Ruby String.index(“/”) return -1

I need that the method index return -1 instead of NIL, is there another way? 我需要方法索引返回-1而不是NIL,还有另一种方法吗? (Ruby programming) (Ruby编程)

index="asddsa".index("/")
if index==nil
    puts -1
else
    puts index
end

Just do it yourself: 自己动手做:

index = "asddsa".index("/") || -1

This works because the expression a = b || c 这是有效的,因为表达式a = b || c a = b || c assigns b to a if b is not nil / false , and if b is nil / false , it assigns c to a instead. a = b || c分配ba如果bnil / false ,并且如果bnil / false ,它分配ca代替。 So in this case, when String#index returns nil , it assigns -1 to your index variable (and when it returns a number, it just assigns that to index ). 因此,在这种情况下,当String#index返回nil ,它会为您的index变量分配-1 (当它返回一个数字时,只会将其分配给index )。

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

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