Compare number and its string representation
20,339
Solution 1
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)
Solution 2
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 => true
nil.to_str == "".to_str => true
"ab123".to_str == 123.to_str => false
Author by
Mike Chaliy
Updated on August 23, 2022Comments
-
Mike Chaliy over 1 year
val1 = 1 val2 = "1" if val1 == val2 #< Question is in this line end
How to compare number and its string representation?