Why not frequencies.sort_by!


#1

Why can I use the self assignment operator on some methods (frequencies.reverse!), but not others (frequencies.sort_by! { |word,count| count})?


#2

There is no .reverse method for hashes. That’s why we have to wait for the assignment so we get an array.


#3

Sorry, bad positive example. Why can’t I assign the result of a hash.sort_by call back to the variable with the ! operator?


#4

Because we cannot place an operator between the method call and the block.we pass it.

Better answer would be the error message thrown…

Text please: 
a quick brown fox jumps over the lazy dog
undefined method `sort_by!' for #<Hash:0x000000016a0558>
Did you mean?  sort_by

#5

So that self-assignment syntax only applies to instance methods with zero arguments? Or only when omitting the parens?

I’m software engineer professionally, but Ruby has always been something of a mystery to me. Thanks for helping me out :slight_smile:


#6

The bang operator transforms the method name to call an entirely different method.

sort_by
sort_by!

Two different methods, one of which in this case does not exist. If we separate the operator from the method name it will throw a syntax error since Ruby does not expect it at that point in the expression.

It is better to suss out the docs on bang methods to get a clear idea of what methods have in place equivalents.


#7

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