Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare number and its string representation

val1 = 1
val2 = "1"

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

How to compare number and its string representation?

like image 533
Mike Chaliy Avatar asked Aug 02 '09 20:08

Mike Chaliy


People also ask

How do you compare numbers and strings?

You can convert a numeric string into integer using Integer. parseInt(String) method, which returns an int type. And then comparison is same as 4 == 4 .

How does Python compare numbers and strings?

Python is Operator The most common method used to compare strings is to use the == and the != operators, which compares variables based on their values. However, if you want to compare whether two object instances are the same based on their object IDs, you may instead want to use is and is not .

How do you compare numbers in a string in C++?

Strings in C++ can be compared using either of the following techniques: String strcmp() function. In-built compare() function. C++ Relational Operators ( '==' , '!=

What is compare in string?

compare() is a public member function of string class. It compares the value of the string object (or a substring) to the sequence of characters specified by its arguments. The compare() can process more than one argument for each string so that one can specify a substring by its index and by its length.


2 Answers

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)

like image 133
Sinan Taifour Avatar answered Oct 11 '22 16:10

Sinan Taifour


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
like image 34
Aaron Rustad Avatar answered Oct 11 '22 17:10

Aaron Rustad