[英]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
分配b
到a
如果b
不nil
/ false
,并且如果b
是nil
/ false
,它分配c
到a
代替。 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.