JCLL
JCLL

Reputation: 5545

How to share a method between classes defined via Ruby Struct?

Given a set of classes defined using Structs, like :

K1=Struct.new(:a,:b)
K2=Struct.new(:c,:d)
...

is it still possible to add a single common method :foo to every class defined that way, or do I need a deep refactoring ?

Factoring such behaviors is normally done using inheritance (or mixins), but I don't know if such a factoring is now still possible, starting with such struct-based class definitions.

Upvotes: 1

Views: 119

Answers (1)

Matheus Moreira
Matheus Moreira

Reputation: 17020

You can simply mix a module into both structures.

module A
  def foo
  end
end

B = Struct.new :a, :b do include A end
C = Struct.new :c, :d do include A end

puts B.new.respond_to? :foo  # => true
puts C.new.respond_to? :foo  # => true

See Module#include and Object#extend for detailed documentation on how this works.

Upvotes: 2

Related Questions