tags:

views:

89

answers:

2

Hi,

val1 = 1 val2 = "1"

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

How to compare number and its string representation?

+4  A: 

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)

Sinan Taifour
I'd go with the first suggestion (changing the integer to string), because if you convert a string like "9abc" to integer using to_i, you are given back the integer 9, which might not be appropriate, and possibly lead to bugs if it isn't the intention.
ehsanul
+1  A: 

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
BigCanOfTuna