I'm familiar with Python and Java, and am trying to learn Ruby to broaden my scope a bit.
I'm not quite sure how to conceptualise the "!-notation" of self-assignment. In case I'm not using the right words to describe this, compare:
foo = 'Hello World!'
foo = foo.downcase
and
foo = 'Hello World!'
foo.downcase!
Both end up with foo reading 'hello world!'
. It seems, then, that foo.<method>!
is short-hand for foo = foo.<method>
.
However, this doesn't seem to be universally true. When trying to call sort-by on a hash frequencies
, for example, the suggested method is:
frequencies = frequencies.sort_by { |word, freq|
freq
}
which works. If, however, I try:
frequencies.sort_by! { |word, freq|
freq
}
I get
undefined method `sort_by!' for {<the_contents_of_my_hash>}:Hash
Is !-notation (what is that properly called, by the way?) only available on strings and arrays? Or is there some deeper concept I'm missing?