= Frozen Array and Hash Literals

For Ruby 2.1, a new feature will (probably) be added to allow specifying that a literal String should start out frozen:

str = "mystring"f # str receives a frozen string

This allows the VM to use the same String object each time, and potentially for the same frozen string across many files. It also obviously provides all the immutability guarantees of a frozen string.

I propose this syntax be expanded to arrays and hashes, allowing the creation of pre-frozen array and hash objects.

This feature is being tracked at #8909

= Syntax

The syntax is the same as for a frozen string, using the normal [] or {} followed by the character 'f':

ary = [1,2,3]f
hash = {a: 1, b: 2, c: 3}f

= Result

The resulting array or hash will be frozen before the expression returns.

= Empty Collections

The empty collections [] and {} would have equivalent frozen empty collections []f and {}f.

= Limitations

Frozen arrays and hashes can only be constructed with frozen or literal elements. This guarantees that both the array/hash and the elements contained within are frozen. If the elements are not frozen or literal values, an error will be raised (which exception?).

This does not require that the frozen elements contain no unfrozen objects, but this is recommended. The intent is to guarantee immutability only for the array/hash and the elements contained immediately inside it.

= Implementation Notes

Frozen arrays or hashes containing only literal elements may be optimized to return the same object every time, or across multiple files that have the same frozen array/hash with the same literal elements. Ruby VMs are not required to do this, however and code that relies on object identity is discouraged:

ary[0] and ary[1] may be the same object

ary = [0,1].map { [:foo]f }

not guaranteed by this spec

ary[0].equal? ary[1]

not guaranteed by this spec

ary[0].object_id == ary[1].object_id

The frozen empty collections []f and {}f may also be the same object everywhere, but this is also not guaranteed by this spec and is implementation-specific.