Difference between .sort! and .sort


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<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>

#2

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.

array.sort!

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.


#3

i see i see OK :slight_smile: thank uu


#4

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.


#5

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.


#6

It’s just naming


#7

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