Question

I have across the following syntax in a code snippet, and I'm not sure what it does.

class << PushableModule = Module::new
 def new *args, &blk
   m = Module::new( *args, &blk )
   m.extend Pushable
   m
 end
end

First off, the class or module PushableModule doesn't exist in the file/program, and secondly what appears to be happening is that I'm retrieving its eigenclass and then setting it equal to Module::new prior to defining a block, which I just don't understand. Could someone please explain this to me (as well as what the code snippet actually does)?

Was it helpful?

Solution

You are taking the operator precedence wrong. It means

class << (PushableModule = Module::new)
  ...
end

It creates a module by Module::new, then names it as PushableModule, then opens its eigenclass by <<.

It is overwriting the constructor of PushableModule. Since new should be defined as PushableModule.new, not as an instance method, the definition is done within the eigenclass.

Usually, you don't overwrite new, but define an instance method initialize, but in some special occasions, the new constructor can be rewritten.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top