vendredi 31 juillet 2015

Does #freeze have a use other than preventing modification?

Ruby's standard uri library has many uses of freeze on components which either can't be modified, or where modification will cause no harm:

  user, password = ui.split(':'.freeze, 2)     # from generic.rb

String#split won't modify its arguments, and even if it did, the code would work properly (Ruby will use a new instance of ':' on the next call).

Here are some more uses of freeze on objects that can't change (these are all from generic.rb)

 if @scheme && @scheme != "ftp".freeze 
 v.delete!("\t\r\n".freeze)
 str << ':'.freeze 

Why are there so many instances of seemingly needless calls to #freeze? Does #freeze have a use beyond preventing modification of its receiver?

Aucun commentaire:

Enregistrer un commentaire