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
>
>  def initialize
>    @dependencies = []
>  end
>
>  # intended to be read only access
>  def dependencies
>    @dependencies
>  end
>
>  def addDependency(d)
>    @dependencies << d
>    puts "adding #{d}"
>  end
> 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:

   a = [].freeze
   a << 1          # TypeError: can't modify frozen array


David

-- 
The          Ruby training with D. Black, G. Brown, J.McAnally
Compleat     Jan 22-23, 2010, Tampa, FL
Rubyist      http://www.thecompleatrubyist.com

David A. Black/Ruby Power and Light, LLC (http://www.rubypal.com)