val1 = 1
val2 = "1"
if val1 == val2 #< Question is in this line
end
How to compare number and its string representation?
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 .
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 .
Strings in C++ can be compared using either of the following techniques: String strcmp() function. In-built compare() function. C++ Relational Operators ( '==' , '!=
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.
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 => true
nil.to_str == "".to_str => true
"ab123".to_str == 123.to_str => false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With