1

I have

book_1 = "War & Peace"
book_2 = "The Nest of Gentry"
puts book_1.length
puts book_2.length
print book_1 <=> book_2    

returns a value of 1? Wikipedia says "If the left argument is greater than the right argument, the operator returns 1.". On what basis it is greater than or less than? I have also printed the length of each string, and the first one is smaller than second one. please explain.

Bishisht Bhatta
  • 307
  • 4
  • 16
  • Strings are compared with lexicographical order. (similar to how words are ordered in dictionary book). Length only matter when leading parts are same: `'ban' < 'banner'` – falsetru Dec 16 '15 at 06:51

3 Answers3

3

When comparing two strings, most of programming languages will return the answer to the question "who will you find first in a standard dictionary ?" This is also called "lexicographical order"

Chen Kinnrot
  • 20,609
  • 17
  • 79
  • 141
0

String compare with lexicographical order. Ruby-Doc String

As the mentioned in ruby official documentation If the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered greater than the shorter one. <=> is the basis for the methods <, <=, >, >=, and between?, included from module Comparable. The method String#== does not use Comparable#==.

"abcdef" <=> "abcde"     #=> 1
"abcdef" <=> "abcdef"    #=> 0
"abcdef" <=> "abcdefg"   #=> -1
"abcdef" <=> "ABCDEF"    #=> 1

Hope this help you ...

Gupta
  • 8,882
  • 4
  • 49
  • 59
0

It is hard to believe that nowadays one would prefer Wikipedia to lookup answers on this kind of question. Ruby has a great documentation: String#<=>. By clicking on “toggle source” in the upper right corner of this description, one might easily see that the “default” comparison is being done with rb_str_cmp, which is apparently using “lexicographical order” for sorting. On the other hand, <=> operator is used in all the Comparable scenarios, hence there is a possibility to easily modify sort behaviour for string lists:

class String
  def <=> other
    other = other.to_s unless other.is_a? String # or raise an exception
    self.length <=> other.length
  end
end

["War & Peace", "Zoo", "Aleph", "The Nest of Gentry"].sort
#⇒ ["Zoo", "Aleph", "War & Peace", "The Nest of Gentry"]

In the latter example sorting is being done by the length.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160