Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Frozen objects in Ruby

In Ruby, what does it mean for a String or Array (etc) object to be 'Frozen'? How/where is this property set or modified?

like image 280
Ephemera Avatar asked Jan 16 '13 05:01

Ephemera


1 Answers

It means you cannot modify it. You set it by freeze method.

s = "a"

concat modifies the string instance.

s.concat("b")
# => "ab"

When you freeze the string:

s.freeze

then, you cannot apply concat any more.

s.concat("c")
# => RuntimeError: can't modify frozen String

However, you can apply methods that do not modify the receiver:

s + "c"
# => "abc"
like image 92
sawa Avatar answered Nov 12 '22 22:11

sawa