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 shown
>> by code below).
>>
>> class A
>>
>>   
>> @dependencies = []
>>  
>>
>>  intended to be read only access
>>   
>> @dependencies
>>  
>>
>>   
>> @dependencies << d
>> puts "adding #{d}"
>>  
>> end
>>
>>
>> a = A.new
>> a.addDependency("foo")
>> a.dependencies << "bar" # encapsulation subverted
>>
>> puts a.dependencies # foo and bar both in array
>
> You can freeze the array:
>
>   ݮ>        >
>

You could also dup it:

class A
  def dependencies
    @dependencies.dup
  end
end

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