0

In the code below, Object method clone or dup copies the pointer of q1, and it does not deep copy it.

q1 = Queue.new
q1.push(1) # => 1
q1.push(2) # => 1,2
q2 = q1.clone
q2.pop # => 1
puts q1.size # => 1 (not 2)

I tried this How do I copy a hash in Ruby?, but it does not work either. I want to know why a Queue instance is not deep copied. Is it for thread safety?

Community
  • 1
  • 1
Yan Li
  • 5
  • 2

1 Answers1

1

Each Ruby class is responsible for implementing its own clone and dup behaviour. Sometimes this manifests as a really weak implementation that doesn't do it correctly.

Queue doesn't seem to implement clone, it's not in the documentation, so it's leaning on the Object#clone method that is apparently insufficient for this task. All that does is copy instance variables into a new container, but it doesn't modify the instance variables themselves. Whatever internals Queue uses are unaffected.

So in short, some things can be cloned easily, others are much more difficult.

If you really need to clone a Queue, maybe you can serialize it and deserialize it, though that usually incurs a massive performance penalty.

Queue doesn't seem to support Enumerable so that limits your options for extracting and copying data. I'd guess that the performance concerns of Queue were such that convenience methods like that were omitted.

tadman
  • 208,517
  • 23
  • 234
  • 262