3

I have two numbers of different length:

"103" and "11"

In irb:

2.1.1 :005 > "11" > "103"
=> true 
2.1.1 :006 > "11" < "103"
=> false 

Why does this happen? I understand I can to a .to_i for each string, but if this is a rails query where the column type is string, anything I can do about this?

3
  • Do you want them sorted by length, numeric value, or alphabetically (which is what it appears to be doing)? Commented Apr 21, 2014 at 20:17
  • This sounds like you want sort_by. Or just sort within your database? Commented Apr 21, 2014 at 20:20
  • Can you show the Rails query and what your code context is for making the comparison? It's not clear to me why you can't customize the comparison using .to_i. Commented Apr 21, 2014 at 20:37

3 Answers 3

6

Strings are sorted lexicographically which means that "1" comes after "0", and "103" comes before "11", and before "1122344", and before "1abc".

You cannot compare strings as if they were numbers, you need to parse them as numbers before you can do that.

The only way I can think of, is to make sure they are padded with enough zeroes before they are turned into a string: "000103", "000011"...

Sign up to request clarification or add additional context in comments.

Comments

2

Strings are being compared character by character. Hence '11' > '103' execution stops on a second character and returns true, since '1'.chr > '0'.chr

Comments

1

They are strings. And they are compared by String#ord value. So '1'.ord # => 49 and '0'.ord # => 48. That is why

'11' > '10' # => true
# and
'11' > '100' # => true

as well as

'b' > 'a' # => true
'a'.ord # => 97
'b'.ord # => 98
# and
'b' > 'aaaaa' # => still true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.