问题
I came across a piece of code in a project I'm working on that looks kind of scary. It's supposed to be displaying a +/- delta between two numbers, but it's using a >
to compare strings of numbers instead of numbers.
I'm assuming that the code is working as expected at the moment, so I'm just trying to understand how Ruby is comparing these strings in this case.
Here's an example with the variables replaced:
if '55.59(100)' > '56.46(101)'
delta = '+'
else
delta = '-'
end
回答1:
String
includes the Comparable
module, which defines <
, >
, >=
, etc, based on the base class's compare (<=>
) method. So if string a comes alphabetically prior to string b, a <=> b
returns -1
, and <
returns true
. The same <=>
method is used for sorting strings, so you can imagine that in a sorted array of strings, each string is 'less than' its neighbor to the right.
回答2:
Be very careful when you are comparing string representations of numbers lexicographically. (i.e. first character to first character, second to second...)
irb(main):001:0> '44' < '45'
=> true
irb(main):002:0> '44.123(whatever)' < '99.921(bananas)'
=> true
but
irb(main):003:0> '44.123' < '100'
=> false
irb(main):004:0> '44.123' < '9.123'
=> true
So long as you know that you're always comparing equal-width strings, lexicographic ordering matches numerical ordering. If they don't, bad things start happening (especially when the most-significant digit changes).
来源:https://stackoverflow.com/questions/21618216/comparing-two-strings-using-greater-than-sign-in-ruby