Ruby: comparison of String with String failed (ArgumentError)

10,277

Make sure you return the comparison result from the block you passed to sort!.

Currently, you return nil (the return value of the last statement, the puts) and this leads to unpredictable results.

Change your code to:

books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]

books.sort! {

  |firstBook, secondBook|
  boolean_value = firstBook <=> secondBook
  print "first book is =  '#{firstBook}'"
  print " , second book is = '#{secondBook}'"
  puts  " and there compare result is #{boolean_value}"

  boolean_value  # <--- this line has been added
}

and everything will work.


Offtopic, a few nitpicks:

  • in Ruby, the convention is to separate words with underscore in variable names. For example, you should rename firstBook -> first_book
  • you should be very careful when naming variables. The variable boolean_value is a bit misleading here, because it's not true or false, its -1, 0, or 1.
Share:
10,277
paul
Author by

paul

Updated on June 05, 2022

Comments

  • paul
    paul almost 2 years

    Here is my ruby code:

    books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]
    
    books.sort! {
    
      |firstBook, secondBook|
      boolean_value = firstBook <=> secondBook
      print "first book is =  '#{firstBook}'"
      print " , second book is = '#{secondBook}'"
      puts  " and there compare result is #{boolean_value}"
    
    }
    

    Questions:

    1. This code runs single iteration and then it gives error in 'sort!': comparison of String with String failed (ArgumentError)
    2. When firstbook = "Charlie and the Chocolate Factory" then secondBook should be "War and Peace" but it code chooses "Utopia" to compare. Why?
  • paul
    paul over 9 years
    Superb. Thanks for valuable advice.But why it chose "utopia" to compare as second book.
  • Cristian Lupascu
    Cristian Lupascu over 9 years
    @paul I don't know exactly, but if I were to take a wild guess, I'd say that Ruby is using QuickSort under the cover, and Utopia is chosen as the quicksort pivot. Apparently the middle element is a reasonable candidate for the pivot.