Compare number and its string representation Compare number and its string representation ruby ruby

Compare number and its string representation


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)


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.

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


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"