Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: comparison of String with String failed (ArgumentError)

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?
like image 951
paul Avatar asked Oct 23 '25 04:10

paul


1 Answers

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.
like image 57
Cristian Lupascu Avatar answered Oct 25 '25 17:10

Cristian Lupascu