theideasmith
theideasmith

Reputation: 2925

Self Defining Classes in Ruby?

I'm trying to understand exactly what the piece of code below accomplishes and how it works.

class Nodes < Struct.new(:nodes) #Create a struct with array hash nodes
    def <<(node)
        nodes << node
        self
    end
end

Upvotes: 2

Views: 79

Answers (1)

Stefan
Stefan

Reputation: 114148

Struct.new(:nodes) creates a new anonymous Struct subclass with a single member :nodes. According to the docs you would usually assign it to a constant, e.g.:

Foo = Struct.new(:nodes)
foo = Foo.new([1, 2, 3]) #=> #<struct Foo nodes=[1, 2, 3]>
foo.nodes                #=> [1, 2, 3]

Subclassing Struct.new

class Nodes < Struct.new(...) creates a new class Nodes with the anonymous Struct subclass as its superclass:

Nodes.ancestors
#=> [Nodes, #<Class:0x007fa0320032d0>, Struct, Enumerable, Object, Kernel, BasicObject]
#                       ^
#                       |
#            anonymous Struct sublass

This allows you to call super when overriding methods from the Struct subclass, e.g.:

class Nodes < Struct.new(:nodes)
  def nodes
    super
  end
end

Upvotes: 4

Related Questions