Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two strings using > (greater than sign) in Ruby?

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
like image 265
Andrew Avatar asked Dec 06 '22 03:12

Andrew


2 Answers

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).

like image 86
roippi Avatar answered Feb 15 '23 13:02

roippi


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.

like image 40
Zach Kemp Avatar answered Feb 15 '23 14:02

Zach Kemp