val1 = 1
val2 = "1"
if val1 == val2 #< Question is in this line
end
如何比较数字和它的字符串表示形式?val1 = 1
val2 = "1"
if val1 == val2 #< Question is in this line
end
如何比较数字和它的字符串表示形式?val1.to_str == val2.to_str => true
nil.to_str == "".to_str => true
"ab123".to_str == 123.to_str => false
Integer(val1) == Integer(val2)
我来这里寻找一个简短的解决方案,不是很明确,但据我所知这是最安全的方法。
Integer("123a") # ArgumentError: invalid value for Integer(): "123a"
'123a'.to_i(16)
。一个更好的例子可能是Integer("hello") # ArgumentError: invalid value for Integer(): "hello"
。 - CadoizInteger('010')
返回 8
。(至少在 Ruby 2.7.5 上,可能也适用于其他版本,无论是旧版还是新版。) - David Winieckifinishing_moves
gem有一个#same_as
方法,可以在不进行任何类型转换的情况下执行比较。
val1 = 1
val2 = "1"
val1.same_as val2
# => True
val2.same_as val1
# => True