比较数字及其字符串表示形式

时间:2021-05-19 03:35:54
val1 = 1
val2 = "1"

if val1 == val2 #< Question is in this line
end

How to compare number and its string representation?

如何比较数字及其字符串表示?

4 个解决方案

#1


29  

Convert either to the other, so either:

要么转换为另一个,要么:

val1.to_s == val2 # returns true

Or:

或者:

val1 == val2.to_i # returns true

Although ruby is dynamically typed (the type is known at runtime), it is also strongly typed (the type doesn't get implicitly typecast)

虽然ruby是动态类型化的(类型在运行时是已知的),但是它也是强类型化的(类型不会隐式地进行类型转换)

#2


3  

Assuming you don't know if either one would be nil, an alpha-numeric string or an empty string, I suggest converting both sides to strings and then comparing.

假设你不知道哪一个是nil,字母数字字符串还是空字符串,我建议把两边都转换成字符串,然后进行比较。

val1.to_str    == val2.to_str => true
nil.to_str     == "".to_str   => true
"ab123".to_str == 123.to_str  => false

#3


0  

An important addition to this question:

这一问题的一个重要补充:

Integer(val1) == Integer(val2)

I came here looking for a short solution, not as explicit, but this is as far as I know the safest way.

我来这里是为了寻找一个简短的解决方案,不是很明确,但就我所知,这是最安全的方法。

Integer("123a") # ArgumentError: invalid value for Integer(): "123a"

#4


0  

The finishing_moves gem has a #same_as method that performs the comparison without having to do any typecasting.

finishing_moves gem有一个#same_as方法,用于执行比较,无需进行任何类型转换。

val1 = 1
val2 = "1"

val1.same_as val2
# => True

val2.same_as val1
# => True

#1


29  

Convert either to the other, so either:

要么转换为另一个,要么:

val1.to_s == val2 # returns true

Or:

或者:

val1 == val2.to_i # returns true

Although ruby is dynamically typed (the type is known at runtime), it is also strongly typed (the type doesn't get implicitly typecast)

虽然ruby是动态类型化的(类型在运行时是已知的),但是它也是强类型化的(类型不会隐式地进行类型转换)

#2


3  

Assuming you don't know if either one would be nil, an alpha-numeric string or an empty string, I suggest converting both sides to strings and then comparing.

假设你不知道哪一个是nil,字母数字字符串还是空字符串,我建议把两边都转换成字符串,然后进行比较。

val1.to_str    == val2.to_str => true
nil.to_str     == "".to_str   => true
"ab123".to_str == 123.to_str  => false

#3


0  

An important addition to this question:

这一问题的一个重要补充:

Integer(val1) == Integer(val2)

I came here looking for a short solution, not as explicit, but this is as far as I know the safest way.

我来这里是为了寻找一个简短的解决方案,不是很明确,但就我所知,这是最安全的方法。

Integer("123a") # ArgumentError: invalid value for Integer(): "123a"

#4


0  

The finishing_moves gem has a #same_as method that performs the comparison without having to do any typecasting.

finishing_moves gem有一个#same_as方法,用于执行比较,无需进行任何类型转换。

val1 = 1
val2 = "1"

val1.same_as val2
# => True

val2.same_as val1
# => True