Difference between .sort! and .sort



<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>
My code is fine, i just want to better understand the syntax. What is the difference between using .sort! and .sort ?


library sorting code

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

How might we sort! the books in alphabetical order? (Hint, hint)

puts books.sort!

<do not remove the three backticks above>


Have you read up on the bang operator? In plain terms, that operator tells Ruby to carry out the operation of the method in place. There is no assignment when the bang operator is used.


The array will be sorted next time it is referred.

sorted_array = array.sort

Without the assignment, we would not be able to see the sorted array.


i see i see OK :slight_smile: thank uu


It’s not an operator, it’s part of the method name. They may still have meaningful return values such as whether a change was made.


It’s more of an indicator than part of a name, though, is it not? It merely indicates whether the method acts upon the object itself, or not. Can’t help but call it an operator, in that sense, but I get the distinction you point out. Thanks.


It’s just naming


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.