How is it saving the sorted order and how is it printing

def alphabetize(arr, rev=false)
  if rev
    arr.sort { |item1, item2| item2 <=> item1 }
    arr.sort { |item1, item2| item1 <=> item2 }

books = ["Heart of Darkness", "Code Complete", "The Lorax", "The Prophet", "Absalom, Absalom!"]

puts "A-Z: #{alphabetize(books)}"
puts "Z-A: #{alphabetize(books, true)}"

Output :

A-Z: ["Absalom, Absalom!", "Code Complete", "Heart of Darkness", "The Lorax", "The Prophet"]
Z-A: ["The Prophet", "The Lorax", "Heart of Darkness", "Code Complete", "Absalom, Absalom!"]


I am new to ruby and wanted to know how i am getting this output

  • How is the sorted order being saved, should'nt we use arr.sort! {.....} ?
  • How is puts statement working when the function is not returning any value ?

The above example is from Ordering Your Library section 1


By the (implicit) return from our alphabetize method. Then it's interpolated into the string by puts.

Not sure what you mean. The goal of puts is to display, once it has displayed there's no need for it to return something (but it could return a value, it's just that the people who defined puts thought it wasn't necessary).