Ruby Logical String comparison (eg. "a" > "b")

66 views Asked by At

Hy,

I am trying to understand how Ruby handles strings when comes to logical comparison.

I tried:

"a" > "b" #--> false
"ab" > "b" #--> false
"z" > "az" #--> true
# i even tried
"z" > "abcdefghijklmnopqrstuvwxyz" #--> true

Is like Ruby gives weight to characters from a(the weakest) to z(the strongest) and it doesn't even check furter from the first character only.

I would appreciate a explanation for this phenomenon. Thank you very much.

1

There are 1 answers

1
Eric Duminil On BEST ANSWER

Strings are ordered as in a wordbook.

string1 > string2 is true if string1 appears later in the book than string2.

"a" is on page 1, "b" is on page 30, so "a">"b" is false.

It's the same reason that if you have a folder full of files with numbers in filenames, 10.txt and 11.txt appear between 1.txt and 2.txt

It's called lexicographical ordering, and it ignores the second letters if the first letters are different.