Andrew
Andrew

Reputation: 238617

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

Upvotes: 4

Views: 6629

Answers (3)

A. Ivlev
A. Ivlev

Reputation: 1

If you need to compare strings as float numbers just use it:

if '10.1'.to_f > '9.239'.to_f
  print 'yes'
end

Upvotes: 0

roippi
roippi

Reputation: 25954

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

Upvotes: 10

Zach Kemp
Zach Kemp

Reputation: 11904

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.

Upvotes: 5

Related Questions