Forum: Ruby How to return an unmodifiable but nor frozen array?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F1938de600a3feacd015051492fdaf0f?d=identicon&s=25 LAMBEAU Bernard (Guest)
on 2009-01-08 15:00
(Received via mailing list)
Hi,

Is there a mean to obtain an unmodifiable array which is not frozen?

Assume you're implementing a directed graph with adjacency lists. A
node would like to expose it's outgoing edges (to let users enjoy its
enumerability for example) but you would like to ensure that this
array will not be modified. A solution would be to duplicate it and I
know that efficiency should not be my concern, but ...

blambeau
D547bd74deebf2145ade3a2ac2286ae0?d=identicon&s=25 Markus Schirp (Guest)
on 2009-01-08 15:05
(Received via mailing list)
You can return the array in a container, this container redirects all
"read" operations to the array and does not redirect any "write"
operations.

class ArrayContainer
  def initialize(array)
    @array
  end

  def [](idx)
    @array[idx]
  end

  ... and so on
end

There is a specialized "delegate" class/module in ruby, using it should
result in better performance than the solution in my ArrayContainer
class.

Mfg

Markus
This topic is locked and can not be replied to.