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:
in 'sort!': comparison of String with String failed (ArgumentError)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:
firstBook -> first_bookboolean_value is a bit misleading here, because it's not true or false, its -1, 0, or 1.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With