I just pass into ruby 2.3 with the new frozen_string_literal option.
Over each of my file I add this line :
# frozen_string_literal: true
a = String('test')
a.frozen? # true
a.gsub!('t', 'a') # raise error : OK
It work well but, is there a way to declare something like this :
a = MutableString('test')
a.frozen? # false
a.gsub!('t', 'a') # aesa
Currently I make it work like this :
a = 'test'.dup
a.frozen? # false
a.gsub!('t', 'a') # aesa
But it's a little bit ugly.
The elegant way to achieve this in future Ruby versions is still being discussed . Until then, of course, the best bet would therefore be to avoid it, or to indeed use String#dup
explicitly.
Technically, however, there's nothing to stop you from doing something like this:
def MutableString(x)
x.dup
end
MutableString('...')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.