Q. while the above code does work,why not the below?
arr.keys.map{|e| e.force_encoding('utf-8')} # =>
# ~> -:14:in `force_encoding': can't modify frozen String (RuntimeError)
# ~> from -:14:in `block in <main>'
# ~> from -:14:in `map'
# ~> from -:14:in `<main>'
Since Strings are so commonly used as keys and that having mutable
objects as hash keys requires caution, when Hash#= is given a string
key it duplicates it, freezes the copy and uses the copy as key. When
you call force_encoding on the key, it fails because it can't modify a
frozen string. On the other hand, e + ' test' doesn't modify the string
e; rather it creates a new (not frozen) string which is composed by the
content of e and the content of ' test'.
Excerpts from Love U Ruby's message of 2013-11-24 17:26:40 +0100:
'£2' => 200
# "50p test",
Since Strings are so commonly used as keys and that having mutable
objects as hash keys requires caution, when Hash#= is given a string
key it duplicates it, freezes the copy and uses the copy as key. When
you call force_encoding on the key, it fails because it can't modify a
frozen string. On the other hand, e + ' test' doesn't modify the string
e; rather it creates a new (not frozen) string which is composed by the
content of e and the content of ' test'.
Thanks for your point!! Yes I confirmed the same as below :