3 ms·
The `sorted_list = my_list.sort()` is a bit of an odd case, though, because, as you've written it, `sorted_list` looks like a new list, even though `sort` does
by MrJohz 3y ago
The `sorted_list = my_list.sort()` is a bit of an odd case, though, because, as you've written it, `sorted_list` looks like a new list, even though `sort` does an in-place sort. (Javascript has exactly this problem, where `.sort` mutates the existing list, but can be chained in such a way that it looks like just another step, leading to surprises later on when the input data is suddenly different to how it used to be.)
In that regard, separating `sorted` (immutable, returns a new sorted list) and `sort` (mutates, returns nothing) helps a lot in terms of preventing subtle mistakes.
I don't know how Ruby handles this case though.
- harrisi 3y agoRuby conventionally separates methods which modify the object from ones that don't by appending an exclamation mark to the method name. So `sort` returns a new sorted list, whereas `sort!` modifies the original list.
- regularfry 3y agoStrictly speaking the exclamation mark convention is for things that are "dangerous", in some sense. Modifying in-place is one sort of dangerous, but there are others, Process.exit! being one notable instance where the "modifying in place" thing is a bit of a stretch, and not really the thing you care about.
- chucke 3y ago!-suffixed being dangerous is a rails convention (throws exception). !-suffixed methods are a ruby convention for instance mutation. Calling mutation dangerous isn't a justification for your argument, as there are intrinsic benefits to using those where justified and contained, such as memory savings.
- regularfry 3y agoThat's simply not true. matz has said this explicitly in the past: > The bang (!) does not mean “destructive” nor lack of it mean non destructive either. The bang sign means “the bang version is more dangerous than its non bang counterpart; handle with care”. Since Ruby has a lot of “destructive” methods, if bang signs follow your opinion, every Ruby program would be full of bangs, thus ugly. (from https://www.ruby-forum.com/t/conventions-in-ruby-and-the-principle-of-least-surprise/158706/2 https://www.ruby-forum.com/t/conventions-in-ruby-and-the-pri..., a quote from 2009)
- harrisi 3y agoThanks for the added information. I'll argue that `Process.exit!` does modify the state of the program in place (which isn't the typical thing one thinks of when thinking of values). Without the bang, it's just a function call that throws an error, which can be caught and handled, so the logical state machine is unchanged. With the bang, it replaces the set of states the current program can be in to a single exit node.
- regularfry 3y agoThat's exactly what I meant about the modification of the state in that case not being what you care about. Technically true, actually irrelevant. Mostly.