Ruby - Subclassing array to make it randomize when flattened

Posted by Markus O'Reilly on Stack Overflow See other posts from Stack Overflow or by Markus O'Reilly
Published on 2010-03-24T11:09:27Z Indexed on 2010/03/24 11:13 UTC
Read the original article Hit count: 366

Filed under:
|
|
|

I'm trying to subclass Array in ruby to make it randomize its elements when flatten! is called. Looking at the source code for Array#flatten (http://ruby-doc.org/core/classes/Array.src/M002218.html), it looks like it should recursively call flatten! on any array contained within an array. So, I tried doing something like this:

class RandArray < Array
    def randomize!
        self.sort!{rand(3)-1}
    end
    def flatten!
        randomize!
        super
    end
end

However, when a normal array contains my RandArray and flatten is called on the normal array, flatten! is never called in my array. I figure ruby is just calling some other method to flatten the arrays recursively, but I can't figure out what that is. Any tips?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about array