Why can you safely use a string as a hash key, even though a string is mutable?
Why can you safely use a string as a hash key, even though a string is mutable?
In Ruby, strings are indeed mutable, meaning their content can be altered after they are created. However, when strings are used as keys in a hash, Ruby internally duplicates and freezes these strings, effectively making them immutable within the context of being a hash key. This process ensures that the string's hash value remains constant, which is crucial for the correct operation of the hash.
When a string is used as a hash key, Ruby calls the freeze
method on the string, which prevents any modifications to it. This frozen string is then used to compute the hash value. If the string were allowed to change after being used as a key, its hash value would also change, leading to potential errors in data retrieval from the hash. By freezing the string, Ruby ensures that the hash value remains consistent, and the integrity of the hash structure is maintained.
This behavior is part of Ruby's design to ensure that mutable objects like strings can be safely used as hash keys without the risk of runtime errors due to changes in the object after it has been used as a key. This approach allows developers to use strings conveniently as hash keys while maintaining the performance and reliability of the hash data structure[8][16].
Citations:
[1] https://stackoverflow.com/questions/40172567/how-to-create-hash-with-string-keys-by-default
[2] https://www.jvt.me/posts/2019/09/07/ruby-hash-keys-string-symbol/
[3] https://www.pluralsight.com/...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào