2009/11/6 David A. Black <dblack / rubypal.com>:
> Hi --
>
> On Fri, 6 Nov 2009, James French wrote:
>
>> Hi,
>>
>> Is there any way of providing read only access to an array? (problem sho=
wn
>> by code below).
>>
>> class A
>>
>> =A0def initialize
>> =A0 @dependencies =3D []
>> =A0end
>>
>> =A0# intended to be read only access
>> =A0def dependencies
>> =A0 @dependencies
>> =A0end
>>
>> =A0def addDependency(d)
>> =A0 @dependencies << d
>> =A0 puts "adding #{d}"
>> =A0end
>> end
>>
>>
>> a =3D A.new
>> a.addDependency("foo")
>> a.dependencies << "bar" # encapsulation subverted
>>
>> puts a.dependencies =A0 # foo and bar both in array
>
> You can freeze the array:
>
> =A0a =3D [].freeze
> =A0a << 1 =A0 =A0 =A0 =A0 =A0# TypeError: can't modify frozen array
>
>

You could also dup it:

class A
  def dependencies
    @dependencies.dup
  end
end

a =3D A.new
a.addDependency "foo"
a.dependencies << "bar"
puts a.dependencies # =3D> ["foo"]