Ruby: String to String comparison 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:

  • This code starts a single iteration and then gives an error in 'sort!': comparison of String with String failed (ArgumentError)

  • When firstbook = "Charlie and the Chocolate Factory" then the secondBook should be "War and Peace" , but he chooses "Utopia" for comparison, Why?
+3


source to share


1 answer


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

.

You are currently returning nil

(the return value of the last operator, puts

), which 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, multiple nitpicks:

  • in Ruby, the convention is to separate underscore words in variable names. For example, you should rename firstBook

    β†’first_book

  • you must be very careful when renaming variables. The variable boolean_value

    here is a little misleading because it is not true

    either false

    , her -1

    , 0

    or 1

    .
+3


source







All Articles